user139301
user139301

Reputation: 354

nodes created within the appendchild argument is not executing

I execute the following lines in Console

thead=document.createElement('thead')
thead.appendChild((document.createElement('th')).appendChild(document.createTextNode('Inner Text')))

But when I execute thead, the return is a 'thead' tag with 'Inner Text' as its content. There is no 'th' tag as per the command execution.

Why does it not work?

Upvotes: 1

Views: 4841

Answers (2)

xdazz
xdazz

Reputation: 160893

.appendChild() returns the appended child:

var thead=document.createElement('thead');
var th = document.createElement('th');
th.appendChild(document.createTextNode('Inner Text'));
thead.appendChild(th);

If you want to do this in one line, you could call the .parentNode of the added node:

thead.appendChild(document.createElement('th').appendChild(document.createTextNode('Inner Text')).parentNode)

Upvotes: 3

alex
alex

Reputation: 490433

node.appendChild() returns the appended element.

The appendChild method returns a reference to added node.

Source

You'd want to break it up something like this...

var thead = document.createElement('thead');
var th = document.createElement('th');
thead.appendChild(th);
th.appendChild(document.createTextNode('Inner Text')));

Upvotes: 1

Related Questions