Reputation: 515
I'm trying to figure out what is the differences between this two:
// first one
var h1 = document.createElement('h1');
var t = document.createTextNode('hey');
h1.appendChild(t);
document.body.appendChild(h1);
// second one
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')));
The first (Document.createElement()) works perfectly, but the second (Document.createTextNode()) does not.
Upvotes: 4
Views: 4900
Reputation: 515
I find a way to do it: (just add .parentNode at the end)
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')).parentNode);
Upvotes: 0
Reputation: 944538
The return value of appendChild
is the appended child.
So if we add variables to:
document.body.appendChild(document.createElement('h1').appendChild(document.createTextNode('hey')));
it gets broken down into:
var text = document.createTextNode('hey');
var h1 = document.createElement('h1');
h1.appendChild(text);
document.body.appendChild(text);
Appending the text
to the body
removes the text
from the h1
.
The h1
is discarded because it is never appended anywhere.
Upvotes: 3