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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

highlight words 1

Status
Not open for further replies.

corwin666

Programmer
Apr 29, 2002
5
FR
I'd like to highlight some words ( if they exist )when I load any html page. Is it possible to do this in javascript ?
 
The easy way to do this is to do it with a combination of server side and client side CSS.

<style>
.words { background-color: yellow ; }
</style>

Your search for <span class=words>duffy</span> :

<span class=words>Duffy</span> is in the market for beer.

One the server side you can replace the words duffy with <span class=words>duffy</span>

I cannot see any easy way to do this on the client side. Sorry. Gary Haran
 
There is a client side method for IE 4 and up. Follow this example and see if you can extrapolate what you need.
Code:
...
<script>
var range
function hiliteText(string) {
  range = document.body.createTextRange()
  if (range.findText(string)) {
    range.expand(&quot;word&quot;)
    range.execCommand(&quot;ForeColor&quot;,&quot;false&quot;,&quot;red&quot;)
  }
}
</script>
</head>
<body bgcolor=white text=black onload=&quot;hiliteText('search string')&quot;>
...
of course it isn't great to hard code the string to search for, but you can get creative with the createTextRange stuff.

Note: this is an IE only method, and it has some bugs on Macintosh. So consider your audience and their browsers before trying this script.
Einstein47
(Love is like PI - natural, irrational, endless, and very important.)
 
that works indeed. Here is a modification that will stop it from blowing up in browser that do not support the createTextRange method :

<script>
function hiliteText(string)
{
if (document.body && document.body.createTextRange)
{
var range = document.body.createTextRange()
if (range.findText(string))
{
range.expand(&quot;word&quot;)
range.execCommand(&quot;ForeColor&quot;,&quot;false&quot;,&quot;red&quot;)
}
}
}
</script>
</head>
<body bgcolor=white text=black onload=&quot;hiliteText('search string')&quot;> Gary Haran
 
Thank you very much xutopia and einstein for your precious help.
 
xutopia,

You are far too kind. I learn a ton from you and the other 'xperts here. I feel honored that something I have shared has been considered valuable.

Thank you for your kind star :)I Einstein47
(Love is like PI - natural, irrational, endless, and very important.)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top