如何在使用jQuery:contains时忽略后代元素中的匹配 [英] How to ignore matches in descendent elements when using jQuery :contains

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

问题描述

我查看了 jQuery选择器,直接包含元素文字?,但建议的解决方案都涉及到。



我尝试选择第二个 div ,其中包含以下文本。

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

jQuery命令:

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

不幸的是,这也会选择(使红色) div 的所有父元素 div 这是因为:contains 会在所选元素及其后代中查找匹配项。



是否有类似的命令,它不会在后代中查找匹配项?我不想选择所有父 divs ,只是 div 直接包含文本。

解决方案

那么probem就是 $('div:contains(mytext)')将匹配包含 myText 的所有 divs code> text或其子节点包含它。



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

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

演示:

演示:

').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时忽略后代元素中的匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆