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
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
Share Improve this question asked Dec 8, 2012 at 18:57 lnelson92lnelson92 6215 gold badges20 silver badges27 bronze badges3 Answers
Reset to default 8You 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).
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");
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>