kanchan
kanchan

Reputation: 15

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?

Upvotes: 1

Views: 4985

Answers (2)

Nawab Ali
Nawab Ali

Reputation: 580

`try to put all of these within the same function as a local variables of that function.

  1. const new_item = getElementById(elementID) // element you want to clone.
  2. const cln = new_Item.cloneNode(true);
  3. getElementById(elementID).appendChild(cln) // that element to which you want to append a new clone.

// I declared and initialized 1 and 2 out of the function where 3 was present.`

Upvotes: 0

Trash Can
Trash Can

Reputation: 6824

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;

Upvotes: 5

Related Questions