Skip to content

Instantly share code, notes, and snippets.

@pstaender
Created April 14, 2021 17:38
Show Gist options
  • Save pstaender/8f1afa27cd9146803daf55b9acdcf1cc to your computer and use it in GitHub Desktop.
Save pstaender/8f1afa27cd9146803daf55b9acdcf1cc to your computer and use it in GitHub Desktop.
Finds all (case-insensitive) text occurrences. Beware: replaces html, so event listener will get lost
window.highlightText = (element, highlightText, styleOrClass = 'highlight') => {
let elements = [];
let html = element.innerHTML;
let newHTML = [];
let style = '';
let klass = '';
if (styleOrClass.includes(':')) {
style = styleOrClass;
} else {
klass = styleOrClass;
}
for(let i=0; i < html.length; i++) {
if (html[i] === '<') {
elements.unshift('<');
} else if ((html[i] === '>') && (elements[0] === '<')) {
elements.shift()
}
if ((elements.length === 0) && (html[i] !== '>')) {
// we are not in a tag attribute area
let nextText = html.substr(i, highlightText.length);
if (nextText.toLowerCase() === highlightText.toLowerCase()) {
newHTML.push(`<span class="${klass}" style="${style}">${nextText}</span>`)
i = i + nextText.length - 1;
} else {
newHTML.push(html[i]);
}
} else {
newHTML.push(html[i]);
}
}
element.innerHTML = newHTML.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment