This article introduces how to highlight and colorize specific text strings on a page using the JavaScript library Mark.js.
With the JavaScript library mark.js, you can easily highlight text strings.
function dynamicallyLoadScript(url) {
var script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
}
// Load the library
dynamicallyLoadScript('https://cdnjs.cloudflare.com/ajax/libs/mark.js/8.11.1/jquery.mark.es6.min.js')
Mark(document.body).mark("a") // => Highlight the string "a".
At first, I tried to do it like document.body.innerHTML = document.body.innerHTML.replace…,
but doing this would break the layout.
However, mark.js somehow doesn’t break it. It’s too good.
Of course, you can also specify objects more precisely with querySelector, and it has quite a lot of depth with features like regular expression search and exclusion.