HTML DOM Range extractContents() Method

The extractContents() method moves the contents of the Range from the document tree into a document object variable. The contents of the Range gets removed from the document tree.

The extractContents() method is similar to the cloneContents() method. The extractContents() method creates a DocumentFragment object from the contents of a Range object and it removes the contents of the Range from the document tree.

Syntax:

documentFragment = range.extractContents();

Parameters: This method does not accept any parameters.

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 an element using this method.

HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML DOM range extractContents() method
    </title>
</head>
  
<body>
    <h1>GeeksforGeeks</h1>
  
    <p>RANGE CONTENT</p>
  
  
    <button onclick="extract()">
        Click to Extract the Range
    </button>
  
    <h1 id="element">
        Below is extracted range: 
    </h1>
  
    <script>
        var range = document.createRange();
  
        range.selectNode(document
            .getElementsByTagName("p").item(0));
  
        const element = 
            document.getElementById('element');
  
        function extract() {
            var documentFragment = 
                    range.extractContents();
                      
            console.log(documentFragment);
            element.appendChild(documentFragment);
        }
    </script>
</body>
  
</html>

chevron_right


Output:
 

  • Before Click the Button:

  • After Click the Button:

Supported Browsers:

  • Google Chrome
  • Edge
  • Firefox
  • Safari
  • Opera
  • Internet Explorer

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.