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

左心房为你撑大大i 提交于 2019-11-26 16:43:03

问题


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?


回答1:


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



回答2:


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



回答3:


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.




回答4:


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



回答5:


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.




回答6:


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




回答7:


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>​]



回答8:


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"



来源:https://stackoverflow.com/questions/1643349/is-there-any-way-to-find-an-element-in-a-documentfragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!