问题描述
我查看了,但建议的解决方案都涉及到。
我尝试选择第二个的所有 divs code> text或其子节点包含它。
您可以使用 id 或者 class ,所以你的选择器将是特定的案例:
$('div.special:contains(mytext)')。css(color,red );
演示: 在你的特定情况下,在选择器中使用resitriction以避免具有的子节点的div:not(:has(> div)): 演示: ').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. The jQuery command: 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: Demo: Or, in your specific case, use a resitriction in your selector to avoid the divs that has child nodes with :not(:has(>div)): Demo: 这篇关于如何在使用jQuery:contains时忽略后代元素中的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
$('div:not(:has(> div)):contains(mytext)')。css(color, 红);
<div>
<div>
mytext
</div>
</div>
$('div:contains("mytext")').css("color", "red)
$('div.special:contains("mytext")').css("color", "red");
$('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>
$('div:not(:has(>div)):contains("mytext")').css("color", "red");
$('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>