jQuery:按文字查找元素

sis*_*sko 285 jquery text find

任何人都可以告诉我,是否可以根据其内容而不是ID找到元素?

我试图找到没有不同类或id的元素.(然后我需要找到该元素的父级.)

Roc*_*mat 404

您可以使用:contains选择器根据其内容获取元素.

$('div:contains("test")').css('background-color', 'red');
Run Code Online (Sandbox Code Playgroud)

在这里演示

  • @DipuRaj:你必须使用[`.filter`](http://api.jquery.com/filter/).`$('div').filter(function(){return $(this).text().toLowerCase()==='test';})` (117认同)
  • 是的,请使用appraoch**@ RocketHazmat**使用,假设您有5个元素全部**前缀为"注册合同"**并且每个元素都有一个数字后缀.你最终会**选择它们**,实际上你只需要带有文字的元素:**'注册合同26'**. (5认同)
  • 很好,但它区分大小写。无论如何我们可以进行不区分大小写的搜索吗? (3认同)
  • 如果它可以帮助其他喜欢在括号中使用空格的人,则以下内容**不起作用**: `$('div:contains( "test" )').css('background-color', 'red ');` (2认同)
  • 如果您在整个页面上运行它,这将不起作用,因为所有 div 都将包含所需的文本。强烈建议检查是否还有其他孩子。 (2认同)
  • 不好。如果是嵌套的“div”,这将返回所有“div”,直到根 div,即查询开始的位置。 (2认同)

yoa*_*nea 88

在jQuery文档中,它说:

匹配的文本可以直接出现在所选元素中,任何元素的后代或组合中

因此,使用:contains() 选择器是不够的,还需要检查您搜索的文本是否是您要定位的元素的直接内容,如下所示:

function findElementByText(text) {
    var jSpot = $("b:contains(" + text + ")")
                .filter(function() { return $(this).children().length === 0;})
                .parent();  // because you asked the parent of that element

    return jSpot;
}
Run Code Online (Sandbox Code Playgroud)

  • 刚遇到这个确切的问题.这应该更高. (3认同)
  • 在以下情况下,该解决方案可能会失败:<li>你好<a href='#'>世界</a>,你好吗。`。我认为,如果在这里搜索“如何”,条件将失败。 (2认同)

Mor*_*rgs 20

费拉斯,我知道这已经老了,但是嘿,我有这个解决方案,我觉得比所有人都好.首先,克服了jquery:contains()随附的Case Sensitivity:

var text = "text";

var search = $( "ul li label" ).filter( function ()
{
    return $( this ).text().toLowerCase().indexOf( text.toLowerCase() ) >= 0;
}).first(); // Returns the first element that matches the text. You can return the last one with .last()
Run Code Online (Sandbox Code Playgroud)

希望有人在不久的将来发现它有用.


Ter*_*Lin 16

火箭的答案不起作用.

<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>
Run Code Online (Sandbox Code Playgroud)

我只是在这里修改了他的DEMO,你可以看到根DOM被选中了.

$('div:contains("test"):last').css('background-color', 'red');
Run Code Online (Sandbox Code Playgroud)

在代码中添加" :last "选择器来解决此问题.


rpl*_*ndo 14

在我看来最好的方式.

$.fn.findByContentText = function (text) {
    return $(this).contents().filter(function () {
        return $(this).text().trim() == text.trim();
    });
};
Run Code Online (Sandbox Code Playgroud)


Nic*_*kin 11

下面的 jQuery 选择包含文本但没有子节点的 div 节点,它们是 DOM 树的叶节点。

$('div:contains("test"):not(:has(*))').css('background-color', 'red');
Run Code Online (Sandbox Code Playgroud)
<div>div1
<div>This is a test, nested in div1</div>
<div>Nested in div1<div>
</div>
<div>div2 test
<div>This is another test, nested in div2</div>
<div>Nested in div2</div>
</div>
<div>
div3
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案! (5认同)

Ale*_*pin 9

是的,使用jQuery contains选择器.

  • 呃,不要不:'包含'不能完全匹配,只是针头是否包含在干草堆中(因此名称)...正如其他人在这里所说的那样 (10认同)
  • 这不是答案。 (2认同)