1

I have a <div id="one">this is a sentence</div>

I have a textbox for userinput, if the user types a word which matches any word in div, eg: if user types "this", which is also there in div value, the background color of "this" should be changed, using Javascript

Thanks Sunny.

1
  • Have you tried anything so far? onkeypress is what you need for the input box, followed by a knowledge of working with ranges in a cross browser manner. Commented May 28, 2010 at 7:13

1 Answer 1

1

Try this:

  1. Connect the textbox to a onkeypress event
  2. In the event function, do an filter for each word that is typed, and match it to words in the div.
  3. For each matched word, replace the word in the div with <span style="background-color:yellow;">word</span> by modifying the content of one.innerHTML.

Note, before you modify the div, you should store the original content in a global variable that is used as base for the matching, otherwise, the matching will be cluttered with the <span...> tags.

Sign up to request clarification or add additional context in comments.

3 Comments

its working but after it changes the color, the page refreshes and the changes are undone.
Hi, what if i want to change the color of next word to the matching word. for eg: refering above code(top), "this" is searched string, so i want to color "is". how can i do it in javascript?
Advanced searching/matching can be done by using regular expressions, but I am not an expert there, so others might want to answer this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.