javascriptjquerystringtextnode

Using jQuery to find matching text in any child text node?


I'm a bit rusty on my jQuery (been a few years!) I have to assume this has been asked 100 times but I'm not searching for the right terms it seems.

I'm trying to grab all of the descendant text nodes of an object, and then, if there's a match to a text string, do something with that object. Here's why I have now:

$(".my-item").each(function(){
    var content = $(this).find('*').text();
    if (content.indexOf('mySearchString'>0)){
        //do something
    }
}) 

I can't seem to get this to find all text, however. Just the direct descendents. Sample HTML:

<div class="my-item">
    this text is part of the var 'content'
    <div>
        this text is not
    </div>
</div>

Solution

  • You have to access the textContent of each node, and you could do directly in the filter, and return the matches, or use a regular each loop if you want to work with them directly

    $(".my-item").each(function(){
        var $children = $(this).children();
    
        $children.contents().each(function(i,node){
            if (node.nodeType === 3 && node.textContent.indexOf('mySearchString') !== -1) {
                //do something
            }
        });
    });
    

    FIDDLE