Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to find an element in a documentFragment?

Tags:

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?

like image 430
pkario Avatar asked Oct 29 '09 12:10

pkario


People also ask

How do you use DocumentFragment?

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 .

Does React use DocumentFragment?

Yes, it is. The external library uses document. createDocumentFragment() to create the DocumentFragment. In my React component, I call theExternalLibrary.

What is the difference between append and appendChild?

append() allows you to also append string objects, whereas Node. appendChild() only accepts Node objects. Element. append() has no return value, whereas Node.

What is fragmentation in Javascript?

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.


2 Answers

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 DocumentFragments 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     } } 
like image 179
Stephen Booher Avatar answered Oct 31 '22 01:10

Stephen Booher


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.

like image 28
NickFitz Avatar answered Oct 31 '22 01:10

NickFitz