简体   繁体   中英

appendChild not appending textNode parent

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM