I want to highlight a word in a page without involving the document.body.innerHTML as this totally alters the functionality of the page.
Is there any other way to do it?
Right now I am using this code to highlight
document.body.innerHTML= document.body.innerHTML.replace(/TEST/g, function(m){
return '<span style="background-color:YELLOW">'+m+'</span>'
}
Thank you
If I understand your problem correctly, I would suggest to retrieve the DOM elements with the relevant content, get the content, and finally surround it with a styled span element.
const $matchedElements = document.querySelectorAll("p");
$matchedElements.forEach(($element) => {
if ($element.innerHTML.match("SampleCollected")) {
const $mySpan = document.createElement("span");
$mySpan.style = "background-color:yellow";
$mySpan.innerHTML = $element.innerHTML;
$element.innerHTML = ""
$element.appendChild($mySpan)
}
});
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
<meta charset="UTF-8" />
</head>
<body>
<p>
SampleCollected
</p>
<p>
SampleNotCollected
</p>
<p>
SampleCollected
</p>
<script src="src/index.js"></script>
</body>
</html>