I'm trying to programmatically highlight all occurences of a search word by adding a CSS class like so :
const style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.innerHTML = `
.word-occurence {
background: yellow;
color: red;
font-weight: bold;
cursor: pointer;
}
`;
document.head.append(style)
document.designMode = "on";
window.getSelection().collapse(document, 0);
const word = 'Ubuntu';
while (window.find(word)) {
document.execCommand('insertHTML', false, '<span class="word-occurence">' + window.getSelection() + '</span>');
window.getSelection().collapseToEnd();
}
document.designMode = "off";
It works almost perfectly. When I try this on the default HTML for Apache server on Ubuntu (as can be found here : http://bl.ocks.org/SunDi3yansyah/raw/c8e7a935a9f6ee6873a2/), all the occurences of the word "Ubuntu" turned red on a yellow background but one of them (the 4th one aka the one that is at the beginning of his paragraph) got CSS inline styling instead of the class. It's missing the cursor: pointer and it has an extra font-size: 14.6667px;
I know that document.execCommand is deprecated but I'm super curious: what happened there ?