For an easter egg, I want to be able to replace every word on my webpage with a constant string. Existing questions focus on replacing certain words, elements that don't contain many other elements, or use libraries such as JQuery. Structure should be kept, i.e. <li>Some text <span>link</span> more text</li>
should become <li>Lorem Lorem <span>Lorem</span> Lorem Lorem</li>
.
If I walk the DOM like this:
recur (el) {
if (typeof el === 'undefined') {
el = document.body
}
for (let e of el.childNodes) {
if (e.nodeType === 1) {
recur(e)
} else if (e.nodeType === 3) {
console.log(e)
}
}
}
I get lots of #text
elements and things that look like strings. How can I actually mutate them? I tried assigning to the corresponding elements in the parent array, but that doesn't work:
Uncaught TypeError: Failed to set an indexed property on 'NodeList': Index property setter is not supported.
Is it better to modify the innerHTML attribute on parent nodes of such text nodes?
Or would you recommend a different approach altogether? CSS-only solutions are also great.