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

var oFra = document.createDocumentFragment();
// oFra.[add elements];
oFra.getElementById("myId"); //not in FF

How can I get "myId" before attaching fragment to document?



What about:

var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");"myId";
oFra.getElementById("myId"); //not in FF

Unless you've added the the created div to your document fragment I'm not sure why getElementById would find it?


If you're willing to roll your own getElementById function then you ought to be able to get the reference you're after, because this code works:

var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div"); = "myId";
if (oFra.hasChildNodes()) {
    var i=0;
    var myEl;
    var children = oFra.childNodes;
    for (var i = 0; i < children.length; i++) {
        if (children[i].id == "myId") {
            myEl = children[i];

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'); = 'foo';
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.


NickFitz is right, DocumentFragment doesn't have the API you expect from Document or Element, in the standard or in browsers (which is a shame; it would be really handy to be able to set a fragment's innerHTML.

Even frameworks don't help you here, as they tend to require Nodes be in the document, or otherwise use methods on the context node that don't exist on fragments. You'd probably have to write your own, eg.:

 function Node_getElementById(node, id) {
      for (var i= 0; i<node.childNodes.length; i++) {
          var child= node.childNodes[i];
          if (child.nodeType!==1) // ELEMENT_NODE
          if (
              return child;
          child= Node_getElementById(child, id);
          if (child!==null)
              return child;
      return null;

It would almost certainly be better to keep track of references as you go along than to rely on a naïve, poorly-performing function like the above.

var frag= document.createDocumentFragment();
var mydiv= document.createElement("div"); 'myId';
// keep reference to mydiv

Using jQuery:

// Create DocumentFragment
var fragment  = document.createDocumentFragment(),
    container = document.createElement('div');

container.textContent = 'A div full of text!';
container.setAttribute('id', 'my-div-1');
container.setAttribute('class', 'a-div-class');

// Query container's class when given ID
var div = $('<div></div>').html(fragment);


You have the overhead of creating the div with jQuery, though. A little hacky, but it works.


The best way by far to find out what you can and can't do with a DocumentFragment is to examine its prototype:

const newFrag = document.createDocumentFragment();  
const protNewFrag = Object.getPrototypeOf( newFrag );
console.log( '£ protNewFrag:' ); 
console.log( protNewFrag ); 

I get

DocumentFragmentPrototype { getElementById: getElementById(), querySelector: querySelector(), querySelectorAll: querySelectorAll(), prepend: prepend(), append: append(), children: Getter, firstElementChild: Getter, lastElementChild: Getter, childElementCount: Getter, 1 more… }

... which tells me I can do things like:

const firstChild = newFrag.children[ 0 ];

PS this won't work:

const firstChild = Object.getPrototypeOf( newFrag ).children[ 0 ];

... you'll be told that "the object doesn't implement the DocumentFragment interface"


An external source, listed below, showed the following code snippet:

var textblock=document.createElement("p")
textblock.setAttribute("id", "george")
textblock.setAttribute("align", "center")

Which displays a different way of setting the object's ID parameter.

Javascript Kit - Document Object Methods


My DOM has a #document-fragment under the element tag.

This is what I am using (using jQuery) , Also I have a use case where I have the HTML DOM in a string -

 var texttemplate = $(filecontents).find('template').html();


      <p>?Super produced One?</p>?, 
      <p>?Super produced Two?</p>, 


                "<p>Super produced One</p>
                <p>Super produced Two</p>
                    <p>Super produced Three</p>




Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.