pkario
pkario

Reputation: 2220

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

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?

Upvotes: 26

Views: 26747

Answers (8)

mike rodent
mike rodent

Reputation: 15642

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"

Upvotes: 1

saurshaz
saurshaz

Reputation: 509

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();


 $(texttemplate).children()

      <p>​Super produced One​</p>​, 
      <appler-one>​</appler-one>, 
      <p>​Super produced Two​</p>, 
      <appler-two>​…​</appler-two>]

$(texttemplate).html()

                "<p>Super produced One</p>
                <appler-one></appler-one>
                <p>Super produced Two</p>
                <appler-two>
                    <p>Super produced Three</p>
                    <appler-three></appler-three>
                </appler-two>"


$(texttemplate).find("appler-one")

              [<appler-one>​</appler-one>​]

Upvotes: 0

Zachary Schuessler
Zachary Schuessler

Reputation: 3682

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');
fragment.appendChild(container);

// Query container's class when given ID
var div = $('<div></div>').html(fragment);
console.log(div.find('#my-div-1').attr('class'));

jsFiddle: http://jsfiddle.net/CCkFs/

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

Upvotes: 1

Stephen Booher
Stephen Booher

Reputation: 6542

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

Upvotes: 34

robertc
robertc

Reputation: 75707

What about:

var oFra = document.createDocumentFragment();
var myDiv = document.createElement("div");
myDiv.id="myId";
oFra.appendChild(myDiv);
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?

--edit

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");
myDiv.id = "myId";
oFra.appendChild(myDiv);
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];
        }
    }
}
window.alert(myEl.id);

Upvotes: 2

bobince
bobince

Reputation: 536379

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
              continue;
          if (child.id===id)
              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");
mydiv.id= 'myId';
frag.appendChild(mydiv);
// keep reference to mydiv

Upvotes: 8

Anthony M. Powers
Anthony M. Powers

Reputation: 1377

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

Upvotes: 0

NickFitz
NickFitz

Reputation: 35041

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.

Upvotes: 9

Related Questions