Categories
JavaScript Answers

How to highlight all text occurrences in a HTML page with JavaScript?

Spread the love

Sometimes, we want to highlight all text occurrences in a HTML page with JavaScript.

In this article, we’ll look at how to highlight all text occurrences in a HTML page with JavaScript.

How to highlight all text occurrences in a HTML page with JavaScript?

To highlight all text occurrences in a HTML page with JavaScript, we can use the string replace method.

For instance, we write:

<div>
  foo bar foo baz
</div>

to add a div.

Then we write:

const div = document.querySelector('div')
div.innerHTML = div.innerHTML.replace(/foo/g, (match) => {
  return `<span style="background-color: yellow">${match}</span>`
})

to select the div with querySelector.

And then we add the highlight by using div.innerHTML to get the div’s HTML code.

Then we call replace with a regex to match all instances of 'foo' and a callback that returns 'foo' wrapped with a span with the background color style set to yellow.

Finally, we assign the returned HTML string to div.innerHTML.

As a result, we should see all instances of foo highlighted in yellow on the screen.

Conclusion

To highlight all text occurrences in a HTML page with JavaScript, we can use the string replace method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *