JQuery Find and change style of a string

css, html, javascript, jquery

Solution

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

Problem

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

Original source

Related problems