Is it possible to append a second child into the first appendchild created in a single line of code?
Something like this:
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text)));
This works fine, but i want to know why it doesn't work the same way in a single line of code.
let p = document.createElement('p');
p.appendChild(document.createTextNode('Some Text'));
document.body.appendChild(p);
CodePudding user response:
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text')));
evaluates to
const p = document.createElement('p');
const node = document.createTextNode('Some Text');
document.body.appendChild(node);
because document.createTextNode
is the last thing called, which returns the DOM node of the text
So when you run this, 'Some Text'
is added to the DOM, but it's not actually inside the <p>
tag
CodePudding user response:
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text)));
It should be like this:
document.body.appendChild(document.createElement('p').appendChild(document.createTextNode('Some Text')));