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.

Syntax:

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

Parameters:

HTMLtext
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:
<head>
    <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);
            }
        }
    </script>
</head>
<body>
    <div id="myDiv" style="background:yellow;">
        Some content.
    </div>
    <button onclick="InsertHtmlTxt ();">Insert a button at the beginning of the yellow field!</button>
</body>
Did you find this example helpful? yes no

Supported by objects:

Related pages:

External links:

User Contributed Comments

Post Content

Post Content