Changchao Liu
Changchao Liu

Reputation: 49

two method using appendChild, but the result is different

Help! I use two methods to add child nodes inside the node. But the results are different! Two kinds of code are below. enter image description hereenter image description hereenter image description hereenter image description here

first code:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <ul id="ulid">
            <li>第一个</li>
            <li>第二个</li>
            <li>第三个</li>
        </ul>
        <br/>
        <input type="button" value="添加" onclick="add1();"/>
    </body>
    <script type="text/javascript">
       function add1(){
           var li1 = document.createElement("li")
           var text1 = document.createTextNode("下一个")
           li1.appendChild(text1)
           document.getElementById("ulid").appendChild(li1);
        }
    </script>
</html>

second code:

<!DOCTYPE html>
<html>
    <head></head>
    <body>
        <ul id="ulid">
            <li>第一个</li>
            <li>第二个</li>
            <li>第三个</li>
        </ul>
        <br/>
        <input type="button" value="添加" onclick="add1();"/>
    </body>
    <script type="text/javascript">
       function add1(){
           var li1 = document.createElement("li").appendChild(document.createTextNode("下一个"))
           document.getElementById("ulid").appendChild(li1);
        }
    </script>
</html>

Upvotes: 0

Views: 165

Answers (1)

Musa
Musa

Reputation: 97672

The method appendChild returns the node that was appended, in this case it is the text node.
Then you append the text node to the ul, which removes it from being a child of the li to be a child of the ul.

https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild#Returns

Upvotes: 2

Related Questions