Question

Case I: Working

var k = document.createElement("div"),
t1 = document.getElementById("test1");
k.appendChild(document.createTextNode("inner1"))
t1.appendChild(k);

Output:

<div id="test1">
    <div>inner1</div>
</div>

Case II: Not working

var k = document.createElement("div"),
t1 = document.getElementById("test1");
t1.appendChild(k.appendChild(document.createTextNode("inner1")));

Output:

<div id="test1">inner1</div>

Why in case 2 their is no surrounding div?

Was it helpful?

Solution

In the second snippet you would want to use the parentNode property

var k = document.createElement("div"),
t1 = document.getElementById("test1");
t1.appendChild(
  k.appendChild(
     document.createTextNode("inner1")
  ) //will return the textnode and not the div, 
    //so we need to get parentNode which will be the div
  .parentNode
);

your second snippet evaluates to basically doing this

var textNode = k.appendChild(document.createTextNode("inner1"));
t1.appendChild(textNode);

using the parentNode evaluates to doing this

var textNode = k.appendChild(document.createTextNode("inner1"));
var k2 = textNode.parentNode;
//k === k2
t1.appendChild(k2);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top