I want to highlight specific word (for example- green and blue) written in 10 . I have found a Javascript code that is highlighting the words written anywhere on the page in a, p, button etx. But that code is not highlighting the words written in textarea. The code I found is -
'<p>Hello world lorem ipsum dolor sit amet, consectetur adipisicing
elit. Est vel accusantium
totam, ipsum delectus et dignissimos mollitia!</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Numquam, corporis.
<small>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium autem voluptas
perferendis dolores ducimus velit error voluptatem, qui rerum modi? this is amet in the
wall</small>
</p>
<textarea>hello amet this</textarea>
<style>
.highlight {
background: lightpink;
}
</style>
<script>
function highlight(elem, keywords, caseSensitive = false, cls = 'highlight') {
const flags = caseSensitive ? 'gi' : 'g';
keywords.sort((a, b) => b.length - a.length);
Array.from(elem.childNodes).forEach(child => {
const keywordRegex = RegExp(keywords.join('|'), flags);
if (child.nodeType !== 3) {
highlight(child, keywords, caseSensitive, cls);
} else if (keywordRegex.test(child.textContent)) {
const frag = document.createDocumentFragment();
let lastIdx = 0;
child.textContent.replace(keywordRegex, (match, idx) => {
const part = document.createTextNode(child.textContent.slice(lastIdx, idx));
const highlighted = document.createElement('span');
highlighted.textContent = match;
highlighted.classList.add(cls);
frag.appendChild(part);
frag.appendChild(highlighted);
lastIdx = idx + match.length;
});
const end = document.createTextNode(child.textContent.slice(lastIdx));
frag.appendChild(end);
child.parentNode.replaceChild(frag, child);
}
});
}
highlight(document.body, ['lorem', 'amet', 'autem']);
</script>
'