Thursday, June 7, 2012

Find text string using jQuery?


Say a web page has a string such as "I am a simple string" that I want to find. How would I go about this using JQuery?



Source: Tips4all

5 comments:

  1. jQuery has the contains method. Here's a snippet for you:

    <script type="text/javascript">
    $(function() {
    var foundin = $('*:contains("I am a simple string")');
    });
    </script>


    The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: http://docs.jquery.com/Selectors/contains#text

    One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')

    ReplyDelete
  2. Normally jQuery selectors do not search within the "text nodes" in the DOM. However if you use the .contents() function, text nodes will be included, then you can use the nodeType property to filter only the text nodes, and the nodeValue property to search the text string.


    $('*', 'body')
    .andSelf()
    .contents()
    .filter(function(){
    return this.nodeType === 3;
    })
    .filter(function(){
    // Only match when contains 'simple string' anywhere in the text
    return this.nodeValue.indexOf('simple string') != -1;
    })
    .each(function(){
    // Do something with this.nodeValue
    });

    ReplyDelete
  3. This will select just the leaf elements that contain "I am a simple string".

    $('*:contains("I am a simple string")').each(function(){
    if($(this).children().length < 1)
    $(this).css("border","solid 2px red") });


    Paste the following into the address bar to test it.

    javascript: $('*:contains("I am a simple string")').each(function(){ if($(this).children().length < 1) $(this).css("border","solid 2px red") }); return false;

    If you want to grab just "I am a simple string". First wrap the text in an element like so.

    $('*:contains("I am a simple string")').each(function(){
    if($(this).children().length < 1)
    $(this).html(
    $(this).text().replace(
    /"I am a simple string"/
    ,'<span containsStringImLookingFor="true">"I am a simple string"</span>'
    )
    )
    });


    and then do this.

    $('*[containsStringImLookingFor]').css("border","solid 2px red");

    ReplyDelete
  4. Take a look at highlight (jQuery plugin).

    ReplyDelete
  5. If you just want the node closest to the text you're searching for, you could use this:

    $('*:contains("my text"):last');


    This will even work if your HTML looks like this:

    <p> blah blah <strong>my <em>text</em></strong></p>


    Using the above selector will find the <strong> tag, since that's the last tag which contains that entire string.

    ReplyDelete