var oFra = document.createDocumentFragment(); // oFra.[add elements]; document.createElement("div").id="myId"; oFra.getElementById("myId"); //not in FF
How can I get "myId" before attaching fragment to document?
A common use for DocumentFragment is to create one, assemble a DOM subtree within it, then append or insert the fragment into the DOM using Node interface methods such as appendChild() , append() , or insertBefore() . Doing this moves the fragment's nodes into the DOM, leaving behind an empty DocumentFragment .
Yes, it is. The external library uses document. createDocumentFragment() to create the DocumentFragment. In my React component, I call theExternalLibrary.
append() allows you to also append string objects, whereas Node. appendChild() only accepts Node objects. Element. append() has no return value, whereas Node.
DocumentFragment s are DOM Node objects which are never part of the main DOM tree. The usual use case is to create the document fragment, append elements to the document fragment and then append the document fragment to the DOM tree. In the DOM tree, the document fragment is replaced by all its children.
All of these answers are rather old, from back when querySelectorAll
and querySelector
were not widely available. It should be noted that these two functions which accept CSS selectors as parameters do work on DocumentFragment
s in modern browsers, and should be the preferred way of dealing with the situation in the question. The alternate solutions presented in some of the answers would be a good approach for legacy browsers which did not support querySelectorAll
or querySelector
.
Here is an example usage:
var df = document.createDocumentFragment(); var div = document.createElement('div'); div.id = 'foo'; df.appendChild(div); var result = df.querySelector('#foo'); // result contains the div element
A good implementation should first use object detection to see if the browser supports this. For instance:
function getElementByIdInFragment(fragment, id) { if (fragment.querySelector) { return fragment.querySelector('#' + id); } else { // your custom implementation here } }
No. The DocumentFragment
API is minimal to say the least: it defines no properties or methods, meaning that it only supports the properties and methods defined in the Node
API. As methods such as getElementById
are defined in the Document
API, they cannot be used with a DocumentFragment
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With