0

I found the answer. Insert HTML element two (or more) times using JavaScript

But I need in depth knowledge about this. How does this happened without for loop or cloning?

let strong = document.createElement('strong');
let text = document.createTextNode('text');
strong.appendChild(text);

let p = document.querySelector('p')
p.appendChild(strong);

// let anotherText = document.createTextNode('anotherText');
// document.querySelector('strong').appendChild(anotherText)

document.querySelector('strong').appendChild(text);

if you uncomment lines then anotherText gets added to strong tag. Why the last one is not working?

There is some reference or what?

Parampreet Rai
  • 154
  • 1
  • 12
Tamerlan
  • 119
  • 1
  • 5

2 Answers2

0

let strong = document.createElement('strong');
let text = document.createTextNode('text');
strong.appendChild(text);

let p = document.querySelector('p')
p.appendChild(strong);

// let anotherText = document.createTextNode('anotherText');
// document.querySelector('strong').appendChild(anotherText)

document.querySelector('strong').appendChild(text);
<p></p>

Even if i uncomment the commented line, it does not work. So sotrong is not yet inserted into the document, searching it through querySelector will give undefined. So first it needs to be inserted in the the dom, then your document.querySelector('strong') will work.

Asutosh
  • 1,775
  • 2
  • 15
  • 22
0

Just need more clarification. But this last line cannot work because text node is already added to strong.

strong = document.createElement('strong');
let text = document.createTextNode('text');
strong.appendChild(text); //You already did the same here 

let p = document.querySelector('p')
p.appendChild(strong);

// let anotherText = document.createTextNode('anotherText');
// document.querySelector('strong').appendChild(anotherText)

document.querySelector('strong').appendChild(text); //This is already executed at strong.appendC... 
Dharman
  • 30,962
  • 25
  • 85
  • 135
Parampreet Rai
  • 154
  • 1
  • 12