'JQuery Do something if specific text find in label control

I need to do something if "Door Entry" or "Phone Call" text is found within the label control, as shown in given below HTML code:

if ($("("label[for=risk_form_purpose_of_one]"):contains('Door Entry')")) {
  document.getElementById("add-function").value = "Add Priority Function";
  getDropDownDiv.style.display = "block";
  getDropDownContentDiv.style.display = "block";
  document.getElementById("fieldsetSize").style.height = "1000px";
  dropDownChanged = true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="acdo01" for="risk_form_purpose_of_one">
      <span style="width:1px;"></span>
      <span class="acdo_disabled" style="width:140px;">Door Entry</span>
    </label>


Solution 1:[1]

Use a querySelector() with the following css selector

label.acdo01[for = "risk_form_purpose_of_one"] > span.acdo_disabled

Which means:

  • <label> with class .acdo01 and for risk_form_purpose_of_one
  • Take the child <span> with class acdo_disabled

Then you can use innerHTML to toggle the flag:

const e = document.querySelector('label.acdo01[for = "risk_form_purpose_of_one"] > span.acdo_disabled');

if (e && e.innerHTML === 'Door Entry') {
  console.log('Do something');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="acdo01" for="risk_form_purpose_of_one">
  <span style="width:1px;"></span>
  <span class="acdo_disabled" style="width:140px;">Door Entry</span>
</label>

Solution 2:[2]

You can select all the label[for='risk_form_purpose_of_one'] containing or 'Door Entry' or 'Phone Call' with the following line:

$("label[for='risk_form_purpose_of_one']").filter(":contains('Door Entry'), :contains('Phone Call')");

Then you can loop through the results to take action on those single elements isolated.

Solution 3:[3]

This may help you!!

if ($("label[for='risk_form_purpose_of_one'] span:contains('Door Entry')").length > 0 || $("label[for='risk_form_purpose_of_one'] span:contains('Phone Call')").length > 0) {
  console.log('do your code');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="acdo01" for="risk_form_purpose_of_one">
    <span style="width:1px;"></span>
    <span class="acdo_disabled" style="width:140px;">Door Entry</span>
</label>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 0stone0
Solution 2 Diego De Vita
Solution 3