简体   繁体   English

如何使用 jQuery :contains 选择器选择具有特定文本的中间节点?

[英]How to select middle nodes with specific text using jQuery :contains selector?

I want to get html elements containing specific text, and I used :contains selector.我想获取包含特定文本的 html 元素,我使用了:contains选择器。 However, I'm not getting the nodes that I target.但是,我没有得到我的目标节点。

In this example I'm trying to get all elements that has the 'today?'在这个例子中,我试图获取所有具有“今天?”的元素。 text, even if it's splited with other inline elements like <a> , <span> , <sup> , etc.文本,即使它与其他内联元素(如<a><span><sup>等)分开。

So I expect the result: DIV.some-class, P.another-class所以我期待结果:DIV.some-class, P.another-class

 //let results = $(':contains(today?):not(:has(*))') let results = $(":contains('today?')").not("script") results.each(function() { console.log(`${this.tagName}${this.className ? '.' + this.className : ''}`) }) /** prints HTML, BODY, DIV.content, DIV.some-class, P.another-class */ console.log() let results2 = $(":contains('today?')").not("script").children().filter(function() { return ($(this).text().indexOf("today?") > -1) }).get() results2.forEach(r => { console.log(`${r.tagName}${r.className ? '.' + r.className : ''}`) }) /** prints BODY, DIV.content, DIV.some-class, P.another-class */ console.log() let results3 = $(":contains('today?')").not("script").filter(function() { return ( $(this).clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .filter(":contains('today?')").length > 0) }).get(); results3.forEach(r => { console.log(`${r.tagName}${r.className ? '.' + r.className : ''}`) }) /** prints P.another-class */
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='content'> <div class='some-class'> Hello world! How are you<a> doing today</a>? </div> <div class='some-other-class'> Bye world! </div> <p class='another-class'> Any <b>plans</b> for today? </p> </div>

You can use children() and contains a selector.您可以使用 children() 并包含一个选择器。 Here's a working solution:这是一个有效的解决方案:

 var elements = $('.content').children().filter(":contains('today?')"); var result = $.map(elements, function (el) { return `${el.tagName}${el.className ? '.' + el.className : ''}`; }); console.log(result.join(', '));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='content'> <div class='some-class'> Hello world! How are you<a> doing today</a>? </div> <div class='some-other-class'> Bye world! </div> <p class='another-class'> Any <b>plans</b> for today? </p> </div>

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

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