简体   繁体   中英

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. 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.

So I expect the result: 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. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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