Reputation: 15
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
Reputation: 580
`try to put all of these within the same function as a local variables of that function.
// I declared and initialized 1 and 2 out of the function where 3 was present.`
Upvotes: 0
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