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

pkario picture pkario · Oct 29, 2009 · Viewed 21.7k times · Source
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?

Answer

Stephen Booher picture Stephen Booher · Feb 6, 2012

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
    }
}