frequently ask ? : Computers : Programming : Languages : JavaScript : DHTML

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

11 of 13 people (85%) answered Yes
Recently 5 of 7 people (71%) answered Yes

Entry

How do I mark occurences of a word the user searches for in an HTML page?

Jan 12th, 2001 07:13
Martin Honnen,


Here is an IE4+ example which uses the range object to allow to 
underline or strike all occurences of a work in the page:
<HTML>
<HEAD>
<SCRIPT>
function format (tag, word) {
  var range = document.body.createTextRange();
  range.collapse(true);
  while (range.findText(word, 100000)) {
    range.pasteHTML('<' + tag + '>' + range.text + '<\/' + tag + '>');
    range.collapse(false);
  } 
}
function underline (word) {
  format ('U', word);
}
function strike (word) {
  format ('STRIKE', word);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="gui">
<INPUT TYPE="text" NAME="word" VALUE="Kibo">
<INPUT TYPE="button" VALUE="underline"
       ONCLICK="underline(this.form.word.value)"
>
<INPUT TYPE="button" VALUE="strike"
       ONCLICK="strike(this.form.word.value)"
>
</FORM>
All for Kibology.
<BR>
Kibo is GOD.
<P>
Kibology for all.
</P>
</BODY>
</HTML>