I get infinite loop when trying wrap text in a tag using innerHTML and TreeWalker.
When I remove <mark> tag, it works fine. I don't know why and how to solve this.
node.innerHTML = node.innerHTML.replaceAll(searchValue, `<mark>${searchValue}</mark>`)
this code will cause infinite loop!!
const content = document.querySelector(".content");
function replaceContent(searchValue, replaceValue) {
const walker = document.createTreeWalker(content, NodeFilter.SHOW_ELEMENT);
let node;
while (node = walker.nextNode()) {
if (node.textContent.includes(searchValue)) {
console.log(searchValue);
node.innerHTML = node.innerHTML.replaceAll(searchValue, `<mark>${searchValue}</mark>`)
//console.log(node)
}
}
}
document.querySelector("button").addEventListener("click", () => {
replaceContent("foo")
})
<div class="content">
<p>foobar foo bar</p>
<p>Lorem abc Lorem foo</p>
</div>
<button>click will cause infinite loop</button>
edited
Oh, sorry to ask this question. I've figured it out.
The reason for the infinite loop is NodeFilter.SHOW_ELEMENT.
Just need to add this
function filter(node) {
if (node.tagName === "P") return NodeFilter.FILTER_ACCEPT;
}
document.createTreeWalker(content, NodeFilter.SHOW_ELEMENT, filter)
