在jQuery中搜索具有特定文本的元素 [英] Searching an element with specific text in jQuery

查看:80
本文介绍了在jQuery中搜索具有特定文本的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取一个包含特定文本的元素.当我使用:contains选择器时,结果也是该特定元素的所有父元素.

I want to get an element that contains specific text. When I use the :contains selector, the result is also all of the parents elements of that specific element.

此外,如果实际包含文本的元素多于on,那么选择器的结果将非常繁琐.是否可以仅获取包含特定文本的元素本身?

Also, if there is more than on element that actually contains the text, the result of the selector is very cumbersome. Is it possible to get only the elements themselves which contains the specific text?

谢谢, 乔尔

示例:

<body>
    <div>
        <div>
            <div>text</div>
        </div>
    </div>
</body>

和$("div:contains('text')")结果为:

and $("div:contains('text')") results in:

[<div>​…​</div>​, <div>​…​</div>​, <div>​text​</div>​]

我想要一种仅获取<div>text</div>元素的方法. (我知道我可以使用.get(-1)来获取最后一个元素,但我想知道是否还有其他gemeric.)

I want a way to only get the <div>text</div> element. (I know I can use .get(-1) to get that last element, but I want to know if there is something more gemeric).

推荐答案

您可以尝试以下方法:

$(":contains('text')").each(function() {
  if($(this).find(":contains('text')").length > 0) {
    // ignore. this is just an element containing at least 1 child containing 'text'
  }
  else {
    // this is an element you want, directly contains 'text'
    // .. your code here ..
  }
});

这篇关于在jQuery中搜索具有特定文本的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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