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

限于喜欢 提交于 2019-12-23 15:08:23

问题


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 text as below.

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

The jQuery command:

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

Unfortunately this also selects (makes red) all the parent divs of the div that I would like to select. This is because :contains looks for a match within the selected element and also its descendants.

Is there an analogous command, which will not look for a match in the descendants? I would not like to select all the parent divs, just the div that contains the text directly.


回答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>



回答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>


来源:https://stackoverflow.com/questions/45955530/how-to-ignore-matches-in-descendent-elements-when-using-jquery-contains

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!