0

I have the following simple code where I try to create a div inside another div using appendChild.

let div1 = document.querySelector('div')
let div2 = document.createElement('DIV')
div1.appendChild(div2)
for (let x = 0; x < 100; x++) {
  div1.textContent += "Text "
  if (x <= 30) {
    div2.textContent += 'Yes '
  }
}

console.log(div1)
console.log(div2)
<div></div>
I am not sure why this code doesn't working. The div has already been created but just not appending to the div1.

Could anyone explain me what is wrong with the appendChild? I think there is no syntax problem with appendChild

Thanks for any responds!

James
  • 2,732
  • 2
  • 5
  • 28
  • 3
    This has nothing to do with `appendChild` at all. Read the documentation on [`textContent`](//developer.mozilla.org/docs/Web/API/Node/textContent): _“Warning: Setting `textContent` on a node removes all of the node’s children and replaces them with a single text node with the given string value.”_ – Sebastian Simon Jan 05 '22 at 21:51
  • 1
    Also note that `div2` still exists, it's just no longer in the DOM. Re-append it after your for-loop. – connexo Jan 05 '22 at 22:05
  • Consider `document.querySelector("div").append(Object.assign(document.createElement("div"), { textContent: "Yes ".repeat(31) }), "Text ".repeat(100));`. Is this what you were after? – Sebastian Simon Jan 05 '22 at 22:14
  • @SebastianSimon, thank for pointing out my error. I have read the documentation. Thank you! Also, the code you provided is the effect I want to trigger. Thanks! – James Jan 05 '22 at 22:23
  • @connexo thank you for pointing out my error! – James Jan 05 '22 at 22:23

0 Answers0