You are here: Reference > JavaScript > client-side > selection and ranges > methods > createContextualFragment (Range)

createContextualFragment method (Range)

Browser support:
Creates a DocumentFragment object from the specified HTML formatted text.
The createContextualFragment method is useful if you want to create a DocumentFragment object with initial content. If you want to build a DocumentFragment object from the contents of a Range object, use the cloneContents method.


object.createContextualFragment (HTMLtext);
You can find the related objects in the Supported by objects section below.


Required. String that specifies the HTML formatted text to insert.

Return value:

Returns the newly created DocumentFragment object.

Example HTML code 1:

This example illustrates the use of the createContextualFragment method:
    <script type="text/javascript">
        function InsertHtmlTxt () {
            var htmlTxt = "<button onclick='alert (\"Hi!\");'>Say Hi!</button>";

            var div = document.getElementById ("myDiv");

            if (document.createRange) {     // all browsers, except IE before version 9
                var rangeObj = document.createRange ();
                if (rangeObj.createContextualFragment) {        // all browsers, except IE
                    var documentFragment = rangeObj.createContextualFragment (htmlTxt);
                    div.insertBefore (documentFragment, div.firstChild);
                else {      // Internet Explorer from version 9
                    div.insertAdjacentHTML ("afterBegin", htmlTxt);
            else {      // Internet Explorer before version 9
                div.insertAdjacentHTML ("afterBegin", htmlTxt);
    <div id="myDiv" style="background:yellow;">
        Some content.
    <button onclick="InsertHtmlTxt ();">Insert a button at the beginning of the yellow field!</button>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content