JSFiddle - React, Tailwind, and code Playground
HTML
<button onclick="Highlighter.highlight('test','yellowgreen');">highlight</button>
<button onclick="Highlighter.unhighlight();">unhighlight</button>
<div contentEditable=true>This is a te<b>st of</b> the highlighting system.</div>
JavaScript
Highlighter = (function() {
var highlighting = false;
document.addEventListener('DOMNodeInserted', function(e) {
if (highlighting) {
var target = e.target;
if (target.nodeType == 1) {
target.className = CLASS_NAME;
}
}
}, false);
var CLASS_NAME = 'highlighted';
return {
highlight: function(text, color) {
highlighting = true;
var sel = window.getSelection();
sel.collapse(document.body, 0);
if (window.find(text, true)) {
document.execCommand("hiliteColor", false, color);
sel.collapseToEnd();
}
highlighting = false;
},
unhighlight: function() {
var highlighted = document.querySelectorAll('.' + CLASS_NAME);
var i = highlighted.length;
while (i--) {
var node = highlighted[i];
node.parentNode.replaceChild(node.firstChild, node);
}
}
}
})();