Select only elements who directly contain text [du

2020-03-12 07:09发布

So I have something like this:

<div class="main">
  <div class="useless">
    text I don't want.    
  </div>
  <div class="useless">
    text I don't want.    
  </div>
  <div class="narrow">
    text I'm searching for
  </div>
  <div class="useless">
    text I don't want.    
  </div>
  <div class="useless">
    text I don't want.    
  </div>
</div>

Using jQuery's lovely :contains selector, I can search for a keyword, but it will return both the parent and the child.

I'd like it to only return elements who directly contain the word for which I'm searching.

Stackoverflow usefully suggested this link as a previous attempt, but it seems extremely clunky since it's crawling all dom nodes and requires a lot of unclear code.

标签: jquery
3条回答
Anthone
2楼-- · 2020-03-12 07:42

The solution, which is provided in the other question as referenced above but as a not highly regarded solution apparently, is to do this:

$("div:contains('searching')").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('searching')").length > 0)
}).css('border', 'solid 1px black');

I'd add it's less clunky than writing a huge thing to crawl all DOM nodes, and really should affect less places when narrowly scoped.

If anyone else has better ideas, I'm definitely interested.

http://jsfiddle.net/TT7dR/42/

查看更多
Animai°情兽
3楼-- · 2020-03-12 07:50

Try This In JS

$('div >:contains("text Im searching for")')
查看更多
Viruses.
4楼-- · 2020-03-12 07:59

This script will find all nodes that contain a specific text. It will also allow you to do any string tests on the text (regex etc).

function getNodesThatContain(text) {
    var textNodes = $(document).find(":not(iframe, script, style)")
      .contents().filter( 
          function() {
           return this.nodeType == 3 
             && this.textContent.indexOf(text) > -1;
    });
    return textNodes.parent();
};

console.log(getNodesThatContain("test"));

Here is a fiddle for testing: http://jsfiddle.net/85qEh/4/

PS - For increased speed use a different top level selector. For example if you only need inside #container then you would var textNodes = $('#container')...

查看更多
登录 后发表回答