本文介绍了如何在使用jQuery:contains时忽略后代元素中的匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了,但建议的解决方案都涉及到。



我尝试选择第二个的所有 divs code> text或其子节点包含它。



您可以使用 id 或者 class ,所以你的选择器将是特定的案例:

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

演示:

< script src =https ://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< /脚本>< DIV> < div class =special>或者,您也可以使用mytext< / div>< / div>

在你的特定情况下,在选择器中使用resitriction以避免具有的子节点的div:not(:has(> div)):

  $('div:not(:has(> div)):contains(mytext)')。css(color, 红); 

演示:

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

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.

解决方案

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>

这篇关于如何在使用jQuery:contains时忽略后代元素中的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 08:01