Search code examples
javascriptdomdocumentfragment

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?


Solution

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