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?
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 thenewChild
is already in the tree, it is first removed.Parameters
newChild
of typeNode
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 nodeReturn Value
Node
The node added.
Note the return value.