lnelson92
lnelson92

Reputation: 611

JQuery Find and change style of a string

I need to write a function that will search all the content in my HTML page for a specific string, and if it finds it then change the color of the text.

Is this possible?

Thanks

Upvotes: 3

Views: 10654

Answers (3)

MAnoj Sarnaik
MAnoj Sarnaik

Reputation: 1650

JQuery Find and change style of a string >> Only Copy Paste and run :)

  $('#seabutton').click(function()
        {
            var sea=$('#search').val();
            var cont=$('p').val();
            alert(cont);
            $('p:contains('+sea+')').each(function()
                 {
    /*          $(this).html($(this).html().replace(new RegExp(sea, 'g'),'<span class=someclass>'+sea+'</span>'));
     */            $(this).html($(this).html().replace(
                        new RegExp(sea, 'i'), '<span class=someclass>'+sea+'</span>'
                  )); 
            });

        });
        $('p').click(function()
        {
            $(".someclass").css("color", "black");
        });
        $('#search').blur(function()
        {
            $(".someclass").css("color", "black");

        });

    })


    </script>
    <style type="text/css">
    .someclass {
        color: red;
    }
    </style>
    </head>
    <body>
    <!-- Select Country:<select id="country" name="country">
    </select>
    <table id="state" border="1">


    </table> -->
    <br>
    Enter Text:<input type="text" id="search"/><input type="button" id="seabutton" value="Search"/>
    <div id="serach">
    <p>This is ankush Dapke
    </p>

    </div>
    </body>
    </html>

Upvotes: 0

Ruan Mendes
Ruan Mendes

Reputation: 92274

The problem with dystroy's answer is that it will overwrite the entire HTML, so if you have any handlers within a node containing your text, they will be removed.

The correct solution is to use text ranges to update only the text itself, not all of the HTML around it. See Highlight text range using JavaScript

And for fun, there is a built-in method window.find that works in FF and Chrome. It's not in the standard though and will only find one at a time. Just like ctrl+f.

window.find("anything");

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382102

You could do that :

CSS :

.someclass {
    color: red;
}

Javascript :

$('p:contains('+yourstring+')', document.body).each(function(){
  $(this).html($(this).html().replace(
        new RegExp(yourstring, 'g'), '<span class=someclass>'+yourstring+'</span>'
  ));
}​);​

Note that this would make problems if yourstring is in a tag or an attribute.

Demonstration

Be careful to run this code before you attach handlers to your paragraphs (or the elements inside which could contain yourstring, for example links).

Upvotes: 8

Related Questions