Skip to content Skip to sidebar Skip to footer

How To Ignore Matches In Descendent Elements When Using JQuery :contains

I looked at jQuery selector for an element that directly contains text?, but the suggested solutions were all quite involved. I tried to select the second div, which contains some

Solution 1:

Well the probem is that $('div:contains("mytext")') will match all divs that contains myText text or that their child nodes contains it.

You can either identify those divs with id or a class so your selector will be specific for this case:

$('div.special:contains("mytext")').css("color", "red");

Demo:

$('div.special:contains("mytext")').css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div class="special">
        mytext
    </div>
</div>

Or, in your specific case, use a resitriction in your selector to avoid the divs that has child nodes with :not(:has(>div)):

$('div:not(:has(>div)):contains("mytext")').css("color", "red");

Demo:

$('div:not(:has(>div)):contains("mytext")').css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>
        mytext
    </div>
</div>

Solution 2:

You can find the target div with find() method in jQuery.

Example:

$('div').find(':contains("mytext")').css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>
        mytext
    </div>
</div>

Edit:

Following example with filter() in jQuery.

$('div').filter(function(i) {
  return this.innerHTML.trim() == "mytext";
}).css("color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  test2
  <div>
    test
    <div>
      mytext
    </div>
  </div>
</div>

Post a Comment for "How To Ignore Matches In Descendent Elements When Using JQuery :contains"