DEV Community

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

Highlight Searched text on a page with just Javascript

kapeel kokane
Coder by day, YouTuber by night, Learner at heart!
・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>
Enter fullscreen mode Exit fullscreen mode

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)

supunkavinda profile image
Supun Kavinda

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

mahalde profile image

Hey there, nice article!

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