JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" id="search">
<input type="button" id="button" onmousedown="doSearch(document.getElementById('search').value)" value="Find">
<div id="content">
<p>Here is some searchable text with some lápices in it, and more lápices, and some <b>for<i>mat</i>t</b>ing and more <b>for<i>mat</i>t</b>ing</p>
</div>
JavaScript
function doSearch(text) {
var range, hiliteSpan, hiliteTextNode;
var id = 0;
if (window.find && window.getSelection) {
var sel = window.getSelection();
sel.collapse(document.body, 0);
document.getElementById("button").blur();
while (window.find(text)) {
// Get the selection range
range = sel.getRangeAt(0);
// Create the highlight element
hiliteSpan = document.createElement("span");
hiliteSpan.id = "hilite_" + (++id);
hiliteSpan.style.backgroundColor = "#FF8C00";
hiliteTextNode = document.createTextNode(range.toString());
hiliteSpan.appendChild(hiliteTextNode);
// Replace the selection range content
range.deleteContents();
range.insertNode(hiliteSpan);
// Move the selection immediately after the inserted node so that
// window.find continues from the correct place
range.setStartAfter(hiliteSpan);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
}