javascripthtmldomclonenode

JS and HTML - cloneNode() isn't working


Below code is working as expected.

CloneNode.js

<!DOCTYPE html>
<html>
        <body>
            <script src="../js/CloneNode.js">
            function myFunction(){
                var the_node = document.getElementById("myList").lastChild;
                var the_clone = the_node.cloneNode(true);
                document.getElementById("myList").appendChild(the_clone);
                }
            </script>
            <ul id="myList">
            <li>Good morning</li>
            <li>Hello</li></ul>
            <p>Click on the button to CloneNode()</p>
            <button onclick = "myFunction()">Copy it!</button>
    </body>
</html>

It is working fine for below code also :

<ul id="myList"><li>Good morning</li>
<li>Hello</li></ul>

OR

<ul id="myList"><li>Good morning</li><li>Hello</li></ul>

But when I enter newline before </ul> in above HTML code, like below, I didn't get the output. Hence, no addition of <li> element on the webpage.

<ul id="myList">
<li>Good morning</li>
<li>Hello</li>
</ul>

How can indentation in HTML code affect the output? Or is there anything that I've missed?


Solution

  • Element.lastChild returns TextNode nodes as well as Element nodes, the new line character is resolved as an empty TextNode when queried, so to make it work regardless, change

    var the_node = document.getElementById("myList").lastChild;

    to

    var the_node = document.getElementById("myList").lastElementChild;