Reputation: 9076
Here i have an example where the first child of an unordered list is replaced using element.replaceChild() method.To replace the previous node a textNode is created using documen.createTextNode().But the problem is as its called replaceChild method then it should replace the child.And i am replacing it with a textNode.But surprisingly the replaced child has a bullet tag infront it.As textNode is not a list item then why the bullet tag is not removed.Though the question is not a serious one.Posted it only to meet my curiosity.thanks!!
<!DOCTYPE html>
<html>
<body>
<ul id="myList"><li>Coffee</li><li>Tea</li><li>Milk</li></ul>
<p id="demo">Click the button to replace the first item in the the list</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var textnode=document.createTextNode("Water");
var item=document.getElementById("myList").childNodes[0];
item.replaceChild(textnode,item.childNodes[0]);
}
</script>
</body>
</html>
Upvotes: 1
Views: 82
Reputation: 816910
item
refers to the first li
element. Then you are replacing the first child of li
element (item.childNodes[0]
), which is the text node Coffee
.
You are never replacing the li
element, just its contents.
If you want to replace the li
element, use
var item=document.getElementById("myList");
instead.
Upvotes: 1