有什么方法可以找到 documentFragment 中的元素吗?

发布于 2024-08-09 11:53:13 字数 207 浏览 7 评论 0 原文

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

在将片段附加到文档之前如何获取“myId”?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

深海少女心 2024-08-16 11:53:13

所有这些答案都相当古老,从那时起 querySelectorAllquerySelector 还没有广泛使用。应该注意的是,这两个接受 CSS 选择器作为参数的函数确实可以在现代浏览器中的 DocumentFragment 上工作,并且应该是处理问题中情况的首选方法。对于不支持 querySelectorAllquerySelector 的旧版浏览器,某些答案中提出的替代解决方案将是一个好方法。

这是一个示例用法:

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

一个好的实现应该首先使用对象检测来查看浏览器是否支持此功能。例如:

function getElementByIdInFragment(fragment, id) {
    if (fragment.querySelector) {
        return fragment.querySelector('#' + id);
    } else {
        // your custom implementation here
    }
}

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
    }
}
-黛色若梦 2024-08-16 11:53:13

不。 DocumentFragment API 至少可以说是最小的:它没有定义属性或方法,这意味着它只支持 Node API。由于 getElementById 等方法是在 Document API,它们不能与 DocumentFragment 一起使用。

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.

或十年 2024-08-16 11:53:13

NickFitz 是对的,在标准或浏览器中,DocumentFragment 没有您期望从 DocumentElement 获得的 API(这是一个遗憾; 能够设置片段的 innerHTML 会非常方便,

即使是框架也无法帮助您,因为它们往往要求节点位于文档中,或者以其他方式使用上下文节点上的方法。您可能必须自己编写,例如:

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

在进行过程中跟踪引用几乎肯定比依赖像上面这样的幼稚、性能不佳的函数要好。 。

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

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
猥︴琐丶欲为 2024-08-16 11:53:13

怎么样:

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

除非您已将创建的 div 添加到文档片段中,否则我不确定为什么 getElementById 会找到它?

--edit

如果您愿意推出自己的 getElementById 函数,那么您应该能够获得所需的引用,因为此代码有效:

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

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);
深白境迁sunset 2024-08-16 11:53:13

使用 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/

您需要创建 div 的开销不过,jQuery。有点老套,但它有效。

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.

想你只要分分秒秒 2024-08-16 11:53:13

到目前为止,找出可以使用 DocumentFragment 做什么和不能做什么的最好方法是检查它的原型:

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

我明白

DocumentFragmentPrototype { getElementById: getElementById(),
查询选择器:查询选择器(),查询选择器全部:查询选择器全部(),
前置:前置(),附加:append(),子级:Getter,
第一个ElementChild:Getter,最后一个ElementChild:Getter,
childElementCount:Getter,还有 1 个... }

...这告诉我我可以做这样的事情:

const firstChild = newFrag.children[ 0 ];

PS这不起作用:

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

...你会被告知“该对象没有实现 DocumentFragment 接口”

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"

尴尬癌患者 2024-08-16 11:53:13

下面列出的外部源显示了以下代码片段:

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

其中显示了设置对象 ID 参数的不同方式。

Javascript 套件 - 文档对象方法

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

清晰传感 2024-08-16 11:53:13

我的 DOM 在元素标签下有一个 #document-fragment

这就是我正在使用的(使用 jQuery),我还有一个用例,我在字符串中包含 HTML DOM -

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

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>​]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文