Question

I have this HTML:

<ul id="ulref">
    <li>Joe</li>
    <li>Fred</li>
    <li>Steve</li>
</ul>

and this JS:

ipDOM=document.getElementById("ulref");
x = document.createElement('LI');
y = document.createTextNode("hello");
z = x.appendChild(y);
ipDOM.appendChild(z);

So, the "hello" should be a child TextNode of the new LI, I am thinking, but instead both the LI and TextNode both appear as direct children (siblings) of the parent UL instead. However, if I alter the JS to:

ipDOM=document.getElementById("ulref");
x = document.createElement('LI');
y = document.createTextNode("hello");
ipDOM.appendChild(x).appendChild(y);

and miss out the z stage, the LI is a child of the UL and the Textnode a child of the LI, as I want.

Why doesn't the first way work as I expected? I am constructing the LI and child TextNode beforehand and then putting that pairing into ipDOM, aren't I?

Was it helpful?

Solution

Node.appendChild returns the child that was appended to the node.
So after you append the text node to the li you append it to the ul(removing it from the li)

ipDOM=document.getElementById("ulref");
x = document.createElement('LI');
y = document.createTextNode("hello");
x.appendChild(y);  // append the text node to the li
ipDOM.appendChild(x); //append the li to the ul
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top