DEV Community

loading...
Cover image for Highlight Searched text on a page with just Javascript

Highlight Searched text on a page with just Javascript

comscience profile image kapeel kokane ・1 min read

If you have always wondered about how to highlight text in html, and thought that it would be a daunting task, surprise surprise! 🙇🏽‍♂️

The 'mark' tag

Recently, I came to know about the mark tag. If you surround any text inside of the mark tag, it will automatically get highlighted by the browser in this striking yellow color.

This word is <mark>highlighted</mark>

That makes highlighting searched text quite a simple task then.

I implemented this fiddle that takes an input text and then highlights that text from the paragraph visible in pure HTML, CSS and Javascript.

Here's how:

  • get the searched text.
  • get the entire text.
  • replace all instances of searched_text with searched_text
  • set the new text as the innerHTML.

Here's a fiddle that does the same:

Although it is a pretty rough implementation and a lot of work is needed to make this solution deployment grade (for example, clearing previous highlights), it's still good to know that something that was earlier thought to be difficult is not so.

Discussion (2)

pic
Editor guide
Collapse
supunkavinda profile image
Supun Kavinda

Do you have any idea how to do this when innerHTML already contains HTML tags?

Collapse
mahalde profile image
mahalde

Hey there, nice article!

A solution to clearing the previous highlights would be to get just the text by using innerText instead of innerHTML. :)