W3cubDocs

/Web APIs

Range: createContextualFragment() method

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

The Range.createContextualFragment() method returns a DocumentFragment by invoking the HTML fragment parsing algorithm or the XML fragment parsing algorithm with the start of the range (the parent of the selected node) as the context node. The HTML fragment parsing algorithm is used if the range belongs to a Document whose HTMLness bit is set. In the HTML case, if the context node would be html, for historical reasons the fragment parsing algorithm is invoked with body as the context instead.

Syntax

createContextualFragment(tagString)

Parameters

tagString

Text that contains text and tags to be converted to a document fragment.

Return value

A DocumentFragment object.

Examples

const tagString = "<div>I am a div node</div>";
const range = document.createRange();

// Make the parent of the first div in the document become the context node
range.selectNode(document.getElementsByTagName("div").item(0));
const documentFragment = range.createContextualFragment(tagString);
document.body.appendChild(documentFragment);

Specifications

Browser compatibility

Desktop Mobile
Chrome Edge Firefox Opera Safari Chrome Android Firefox for Android Opera Android Safari on IOS Samsung Internet WebView Android WebView on iOS
createContextualFragment 1 12 1 ≤12.1 1 18 4 ≤12.1 1 1.0 4.4 1
enforces_trusted_types 83 83 135 69 26 83 No 59 26 13.0 83 26

See also

© 2005–2025 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Range/createContextualFragment