Reputation: 7602
I am learning the HTML DOM model and i am stuck at a problem.I am unable to understand how does the createDocumentFragment() method works in the following code.
HTML CODE:
<!DOCTYPE html>
<html>
<body>
<ul><li>Coffee</li><li>Tea</li></ul>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var d=document.createDocumentFragment();
d.appendChild(document.getElementsByTagName("LI")[0]);
d.childNodes[0].childNodes[0].nodeValue="Milk";
document.getElementsByTagName("UL")[0].appendChild(d);
};
</script>
</body>
</html>
I understand that createDocumentFragment() method creates a imaginary Node object which is usefull when you want to extract parts of your document.And the appendChild() method appends the node to the last child of a node.But what does the following mean:
d.childNodes[0].childNodes[0].nodeValue="Milk";
Shouldn't it be d.childNodes[0].nodeValue="Milk";
?. Please can someone give me a clear explanation of how the above DOM model is working!.
Upvotes: 2
Views: 108
Reputation: 71918
There is a text node inside the <li>
representing the string "Coffee", and that's what gets replaced with "Milk". The first child of the fragment is the <li>
, whose first child is the text node.
Upvotes: 2