Highlight Searched text on a page with just Javascript

kokaneka

kapeel kokane

Posted on April 20, 2020

Highlight Searched text on a page with just Javascript

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.

💖 💪 🙅 🚩
kokaneka
kapeel kokane

Posted on April 20, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related