Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only elements who directly contain text [duplicate]

Tags:

jquery

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.

like image 525
RandallB Avatar asked Aug 06 '13 18:08

RandallB


1 Answers

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

like image 162
Daniel Moses Avatar answered Nov 15 '22 19:11

Daniel Moses