user7499659
user7499659

Reputation:

Why appendChild() overrides createElement() if it was chained at the end of it?

The Question: I'm trying to understand why I can't chain the appendChild() method to document.createElement() like this:

var listItem = document.createElement('li').appendChild(text);

HTML

<ul>
    <li id="one"><em>fresh</em> figs</li>
    <li id="two">pine nuts</li>
    <li id="three">honey</li>
    <li id="four">balsamic vinegar</li>
</ul>

I know that this is the correct way to do it:

var ul = document.getElementsByTagName('ul')[0];
var txt = document.createTextNode('this is a text string');
var el = document.createElement('li');
el.appendChild(txt);

but why when I do this:

var ul = document.getElementsByTagName('ul')[0]; 
var text = document.createTextNode('I am the first generated list'); 
var listItem = document.createElement('li').appendChild(text); 
ul.appendChild(listItem);

it deletes the li element I formed and add the text ONLY to the ul item! why?

Upvotes: 3

Views: 1200

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115242

Actually, it's not deleting, the appendChild method return the appended child so in the second case, listItem holds the reference of text node which is appended.

var ul = document.getElementsByTagName('ul')[0];
var el = document.createElement('li');
el.appendChild(document.createTextNode('this is a text string'));
// or el.textContent = 'this is a text string';

ul.appendChild(el);
<ul>
  <li id="one"><em>fresh</em> figs</li>
  <li id="two">pine nuts</li>
  <li id="three">honey</li>
  <li id="four">balsamic vinegar</li>
</ul>

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075159

Because appendChild isn't designed to work that way. It could have been, but it wasn't. For it to work that way, appendChild would have to return a reference to the element on which it was called, but it doesn't; it returns the argument you pass to it.

it deletes the li element I formed

No, it doesn't delete it; it never appends it, because listItem is not a reference to the element you created; it's the text node instead. From the DOM3 spec:

appendChild (modified in DOM Level 3)

Adds the node newChild to the end of the list of children of this node. If the newChild is already in the tree, it is first removed.

Parameters

  • newChild of type Node
    The node to add. If it is a DocumentFragment object, the entire contents of the document fragment are moved into the child list of this node

Return Value

  • Node
    The node added.

Note the return value.

Upvotes: 3

Related Questions