繁体   English   中英

jQuery:按文本查找元素

[英]jQuery: find element by text

谁能告诉我是否可以根据元素的内容而不是idclass找到元素?

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

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

演示在这里

 $('div:contains("test")').css('background-color', 'red');
 <div>This is a test</div> <div>Another Div</div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

在 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;
}

伙计们,我知道这是旧的,但是嘿,我有这个解决方案,我认为它比所有解决方案都有效。 首先,最重要的是克服了 jquery :contains() 附带的区分大小写的问题:

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()

希望在不久的将来有人会发现它有帮助。

火箭的回答不起作用。

<div>hhhhhh
<div>This is a test</div>
<div>Another Div</div>
</div>

在这里简单地修改了他的DEMO ,你可以看到选择了根DOM。

$('div:contains("test"):last').css('background-color', 'red');

在代码中添加“ :last ”选择器来解决这个问题。

在我看来最好的方式。

$.fn.findByContentText = function (text) {
    return $(this).contents().filter(function () {
        return $(this).text().trim() == text.trim();
    });
};

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

 $('div:contains("test"):not(:has(*))').css('background-color', 'red');
 <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>

是的,使用 jQuery contains选择器。

到目前为止,所有答案都不匹配包含包含特定文本的直接子文本节点的所有特定元素。

考虑以下示例。 我们要找到所有的霍比特人,即所有包含直接子文本节点的div ,其中包含单词“霍比特人”(包括单词边框,忽略大小写)。

 $(function() { const ELEMTYPE = Node.ELEMENT_NODE const TEXTTYPE = Node.TEXT_NODE /* Behaves a bit like Python's os.walk(). The `topdown` parameter is not strictly necessary for this example. */ function* walk_text(root, topdown=true) { const childs = [] const textchilds = [] for (const child of root.childNodes) { const childtype = child.nodeType if (childtype === ELEMTYPE) { childs.push(child) } else if (childtype === TEXTTYPE) { textchilds.push(child) } } if (topdown) { yield [root, textchilds] } for (const child of childs) { yield* walk_text(child, topdown) } if (!topdown) { yield [root, textchilds] } } function* walk_matching(startnode, nodepat, textpat) { for ( [elem, textchilds] of walk_text(startnode) ) { if ( nodepat.test(elem.nodeName) ) { for ( const textchild of textchilds ) { if ( textpat.test(textchild.nodeValue) ) { yield elem break } } } } } // raw dom node let startnode = $('body')[0] // search for element nodes with names matching this pattern ... let nodepat = /^div$/i // ... containing direct child text nodes matching this pattern let textpat = /\\bhobbit\\b/i for ( const node of walk_matching( startnode, nodepat, textpat ) ) { $(node).css({ border: '1px solid black', color: 'black' }) } });
 div { margin:10px 0; padding: 10px; border: 1px solid silver; color: silver; font-style:italic; } div:before { display:block; content: attr(name); font-style:normal; } /* Inserted by SO, we are not interested in it */ body + div { display: none; }
 <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Find the hobbits</title> </head> <body> <div name='Tolkien'> book writer <div name='Elrond'> elven king <div name='Arwen'>elven princess</div> <div name='Aragorn'>human king, son-in-law</div> </div> <div name='Gandalf'> wizard, expert for hobbits <div name='Bilbo'> old hobbit <div name='Frodo'> young hobbit <div name='Samweis'>best friend hobbit</div> </div> </div> <div name='Gollum'>ex hobbit</div> <div name='Odo'>hobbit</div> </div> </div> <script src= "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> </body> </html>

其他答案找到(搜索“霍比特人”时):

  • Rocket Hazmat 的回答:托尔金、甘道夫、比尔博、佛罗多、萨姆维斯、咕噜、奥多
  • 莫格斯的回答:托尔金
  • yoav barnea 的回答:甘道夫,佛罗多
  • Nicholas Sushkin 的回答: Samweis、Gollum、Odo
  • Rocket Hazmat 在评论中的回答,Terry Lin 的回答,rplaurindo 的回答: Odo

所有这些答案都有意义,这取决于您想要做什么。 明智地选择,因为 Rocket Hazmat 的答案、Morgs 的答案和 Terry Lin 的答案的部分性能比我的解决方案快两倍多。 我想这是因为他们不需要遍历整个 DOM。 大多数使用.filter()答案执行得非常快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM