How to ignore matches in descendant elements when using jQuery: contains

I looked at the jQuery selector for an element that contains only text? , but the proposed solutions were in great demand.

I tried to select the second divone that contains the text as shown below.

<div>
    <div>
        mytext
    </div>
</div>

JQuery command:

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

Unfortunately, this also selects (turns red) all the parent divsof divwhich I would like to select. This is due to the fact that it is :containslooking for a match in the selected element, as well as its descendants.

Is there a similar command that will not look for a match in the descendants? I would not want to select all the parent ones divsthat just divcontain the text directly.

+4
2

, $('div:contains("mytext")') divs, myText .

div id class, :

$('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>
Hide result

, , , divs :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>
Hide result
+2

div find() jQuery.

:

$('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>
Hide result

Edit:

filter() 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>
Hide result
0

Source: https://habr.com/ru/post/1684731/


All Articles