0

I have a parent and I add a child to it. After that I append <br> to the parent's innerHTML, but after that the child's innerHTML can't be changed anymore. What's going on here? Why isn't the final result "bbb"?

But if you comment out container.innerHTML += "<br>", it does change to "bbb".

let container = document.createElement('div')
document.body.appendChild(container)

let child = document.createElement('div')
child.innerHTML = "aaa"
container.appendChild(child)

container.innerHTML += "<br>"
child.innerHTML = "bbb"
stackzebra
  • 450
  • 1
  • 6
  • 13
  • 2
    Replacing `innerHTML` (which is what `+=` does) removes any previously present element references. I suggest if you want to append elements, then use `.append()` or similar DOM methods – Phil Jan 18 '22 at 22:20
  • @Phil But `console.log(child)` after the
    line doesn't give an error, in fact it logs `
    bbb
    ` - the changed html - even though it doesn't change on the page. That's what's confusing!
    – stackzebra Jan 18 '22 at 22:31
  • The `child` element reference still exists (in memory), it just no longer refers to an element in the document. IMO, `innerHTML` is a _hack_ that should be avoided whenever possible – Phil Jan 18 '22 at 22:32

0 Answers0