Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Highlight particular words 1

Status
Not open for further replies.

Geronantimo

Technical User
Joined
Apr 3, 2006
Messages
79
Location
SE
Hi,

I am trying to discover if this is even possible.

Can one use JavScript to hightlight particular words in a web page? The objective will be to have dynamic content, but to have particular words highlighted.

I have been completely unable to find any answers on the web, so I wonder if this can be done.
 
Thanks for your reply Dan,

I failed to clarify that I would like to specify the words that will be highlighted, rather than to return highlighted search terms.

My webpage contain dynamic content and I would to be able to specify which terms are highlighted if they appear in the page.
 
Try something along the lines of...

Code:
// Get body content
var body = document.body.innerHTML;

// Substitute a keyword with new HTML code
body = string.replace("keyword", "<span class='hl'>keyword</span>");

I'm not sure about the document.body.innerHTML part though.
 
Hi Dan,

I was moving fairly quickly and didn't consider the customisation.

However, having now looked properly at google.js, my JavaScript skills cannot cope with the necessary customisation.

I'll have to look for an alternative method.

By the way, I liked your graphics demos @ Code Couch.
 
didn't Kirsle's code work for you? If not, can you tell us what the problem you're having with it is?




I hope this helps;
Rob Hercules
 
I played with the code I posted earlier and did some experimenting.

I came up with this script to replace every instance of "riven" in a page and highlight them in green background.

Here's the code I used (note--put it at the end of your page after the body content is fully defined):
Code:
<script>
var newtxt = "string";
var body = document.body.innerHTML;
newtxt = body;
while (newtxt.indexOf("riven") >= 0) {
	newtxt = newtxt.replace(/riven/, "<span style='background: green'>__temp1__</span>");
}
while (newtxt.indexOf("__temp1__") >= 0) {
	newtxt = newtxt.replace(/__temp1__/, "riven");
}
document.body.innerHTML = newtxt;
</script>

You can copy that pattern for other words. It could probably be made more efficient by using arrays of words too, but you get the basic idea. :-)
 
Hi All,

Kirsle's code was perfect. This is a really useful little piece of JavaScript.

Many, many thanks for all your input.

Ant
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top