Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 757
lnelson92 Avatar asked Jan 20 '26 11:01

lnelson92


1 Answers

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

like image 175
Denys Séguret Avatar answered Jan 23 '26 00:01

Denys Séguret