- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
HTML DOM createDocumentFragment() method
The HTML DOM createDocumentFragment() method is used for creating a document fragment. The document fragment doesn’t affect the DOM structure as it resides in memory. When we append the document fragment to the DOM, it is basically replaced by its children i.e there is no document fragment appended to the document only its children gets appended.
Syntax
Following is the syntax for the createDocumentFragment() method −
document.createDocumentFragment()
It returns a DocumentFragment object, representing the documentFragment node.
Example
Let us look at an example for the HTML DOM createDocumentFragment() method −
<!DOCTYPE html> <html> <body> <h1>createDocumentFragment() example</h1> <p>Click the below button to change list items using the createDocumentFragment method.</p> <button type="button" onclick="changeList()">CHANGE</button> <ul> <li>Mango</li> <li>Peach</li> <li>Guava<li> <li>Strawberry</liv <li>Papaya</li> </ul> <script> function changeList() { var x= document.createDocumentFragment(); x.appendChild(document.getElementsByTagName("LI")[0]); x.childNodes[0].childNodes[0].nodeValue = "Watermelon"; document.getElementsByTagName("UL")[0].appendChild(x); } </script> </body> </html>
Output
This will produce the following output −
On clicking the CHANGE button −
In the above example −
We have created an unordered list with five list items −
<ul> <li>Mango</li> <li>Peach</li> <li>Guava<li> <li>Strawberry</li> <li>Papaya</li> </ul>
We have then created CHANGE button that will execute the changeList() method on being clicked by the user −
<button type="button" onclick="changeList()">CHANGE</button>
The changeList() function creates a document fragment using the createDocumentFragment() method of the document object and assigns it to the variable x. Using the appnedChild() method we make the list element the child of the document fragment. We set the first list element value that is inside the document fragment to “Watermelon”. We then append the document fragment as the last child of the
function changeList() { var x= document.createDocumentFragment(); x.appendChild(document.getElementsByTagName("LI")[0]); x.childNodes[0].childNodes[0].nodeValue = "Watermelon"; document.getElementsByTagName("UL")[0].appendChild(x); }