3

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.

nnnmmm
  • 7,964
  • 4
  • 22
  • 41
  • If it's the same replacement string over and over, you could just count the number of words in an element and then set the nodes `innerHTML` with that many of your new word. – Chris Riebschlager Jan 17 '18 at 22:19
  • 1
    Possible duplicate of [Change textNode value](https://stackoverflow.com/questions/680431/change-textnode-value) – yuriy636 Jan 17 '18 at 22:21
  • Chris: You mean with `innerHTML`? Yes, but what are the relevant elements? What if I have nesting à la `
  • Some text link more text
  • ` – nnnmmm Jan 17 '18 at 22:22
  • Can you provide us a sample input, and a sample output? – Blue Jan 17 '18 at 22:22
  • I added one in the first paragraph of the question. – nnnmmm Jan 17 '18 at 22:25