Skip to content
Advertisement

Highlight text of a DIV as user types characters in an input field

I have seen many posts pertaining to highlighting text in a DIV using javascript, but none do quite what I’m looking for.

What I need to do is highlight the text within a specific DIV, character by character as the user enters the search term. Conversely, as the user backspaces or deletes characters, I need to “de-highlight” the text of the same DIV.

I imagine this has already been done somewhere by someone, but I have not yet found a post here or from Google that behaves exactly as I need.

Any feedback is appreciated.

this code executes as user types characters into an input field. The problem with it is that in some instances, it inserts the string ” ” into the table as I type and I don’t know why, so I’m searching for a different solution.

Thanks for your feedback!

JavaScript

Advertisement

Answer

This can be easily done with a regular expression to change the div’s content. Here’s a simple implementation :

JavaScript

Demonstration (click “Run with JS”)


EDIT :

This more sophisticated version works even if you have tables and stuff :

JavaScript

Demonstration (click “Run with JS”)

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement