DEV Community

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

Posted on

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.

Top comments (3)

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. :)

Collapse
 
betaprojects profile image
betaprojects • Edited

A solution to clearing the previous highlights:
(Changes in bold)

var oldText = document.getElementById("text").innerHTML;
function search(e) {
let searched = document.getElementById("search").value.trim();
if (searched !== "") {
let text = oldText;
let re = new RegExp(searched,"g"); // search for all instances
let newText = text.replace(re, <mark>+searched+</mark>);
document.getElementById("text").innerHTML = newText;
}
}