I\'ve got a little text node:
var node
And I want to wrap a span around every occurrence of \"lol\".
node.nodeValue = node.
An up to date answer for those that are finding this question now is the following :
function textNodeInnerHTML(textNode,innerHTML) {
var div = document.createElement('div');
textNode.parentNode.insertBefore(div,textNode);
div.insertAdjacentHTML('afterend',innerHTML);
div.remove();
textNode.remove();
}
The idea is to insert a newly created html element (lets say var div = document.createElement('div');) before the textNode using :
textNode.parentNode.insertBefore(div,textNode);
and then use :
div.insertAdjacentHTML(
'afterend',
textNode.data.replace(/lol/g,`lol`)
)
then remove textNode and div using :
textNode.remove();
div.remove();
The insertAdjacentHTML does not destroy event listeners like innerHTML does .
If you want to find all text nodes that are descendants of elm then use :
[...elm.querySelectorAll('*')]
.map(l => [...l.childNodes])
.flat()
.filter(l => l.nodeType === 3);