I've seen similar questions to this one, but none solve my problem.
I have a chrome extension where I highlight some content on the page by creating a fragment and replacing characters with spans, like this:
for (const node of textChildNodes(parentNode)) {
const fragment = document.createDocumentFragment();
const matches = node.textContent.match(regex);
const split = node.textContent.split(regex);
split.forEach((content, i) => {
fragment.appendChild(document.createTextNode(content));
if (i !== split.length-1) {
const clone = elem.cloneNode(true);
clone.appendChild(document.createTextNode(matches[i]));
fragment.appendChild(clone);
}
});
node.parentElement.replaceChild(fragment, node);
With "textChildNodes()" being a function that returns only the nodes that are text nodes, like this:
const textChildNodes = obj => Array.from(obj.childNodes)
.filter(node => node.nodeName === "#text");
It works pretty well, as shown in the picture below:
The problem is, in cases like this (as in a Facebook post with a "See more" button), the nodes that were highlighted have the same parent as the node with "See more", as shown in the picture below:
When I click on "See more", the Facebook post disappears and the error below shows up on the console:
This doesn't happen if the button "See more" doesn't have a "sibling" node highlighted.
I have tried changing the fragment with a div and put all text nodes inside spans, but it still happens.
Maybe the parent node, when having it's children changed, loses its "identity", and then when React goes to delete something from it, it crashes? How can I fix it?