Open In App

HTML DOM Range cloneContents() method

Improve
Improve
Like Article
Like
Save
Share
Report

The cloneContents() returns a DocumentFragment object copying the Nodes and Contents included in the Range. All the range contents can be cloned to a DocumentFragment object.

cloneContents() method is similar to extractContents() method but extractContents() method copies the content to an object variable and removes the range content from DOM tree, whereas cloneContents() method copies the content to an object variable but do not removes the range content from DOM tree.

Syntax:

documentFragment = range.cloneContents();

Parameters: This method does not take any parameter.

Return value: This method returns a DocumentFragment object created from the contents of the Range.

Example: This example shows how to create a DocumentFragment object and append it to the document using this method.

HTML




<html>
<head>
<title>HTML DOM range cloneContents() method</title>   
</head>
<body>
    <h1>GeeksforGeeks</h1>
     
 
<p>This is the Range Content</p>
 
 
    <button onclick="clone()">Click To Clone Contents</button>
</body>
<script>
    let range = document.createRange();
    let referenceNode = document.getElementsByTagName('p').item(0);
    range.selectNode(referenceNode);
    function clone(){
        documentFragment = range.cloneContents();
        document.body.appendChild(documentFragment);
        console.log(documentFragment)   
    }
</script>
</html>


Output:

Before Button Click:

After Button Click:

Supported Browsers:

  • Google Chrome 1
  • Edge 12
  • Firefox 1
  • Safari 1
  • Opera 9
  • Internet Explorer 9

Last Updated : 12 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads