开发者

Javascript - document.createDocumentFragment() - referencing a element by ID

开发者 https://www.devze.com 2023-02-02 15:29 出处:网络
Is it possible to refer to a element by its ID while it is inside of a documentFragment before it is appended to the document?

Is it possible to refer to a element by its ID while it is inside of a documentFragment before it is appended to the document?

For example:

var docFragment = document.createDocumentFragment();
var newElem = document.createElement('div');
docFragment.appendChild(newElem);
var newAttrib = document.createAttribute('id');
newAttrib.value = 'myid';
newElem.setAttributeNode(newAttrib);
var newElem2 = document.createElement('span');
docFragment.firstChild.appendChild(newElem2);
var newAttrib = document.createAttribute('id');
newAttrib.value = 'myid2';
newElem2.setAttributeNode(newAttrib);

For some examples, Ive tried this,

alert(docFragment.getElementById('myid').id) <----- but this does not work

alert(docFragment.document.getElementById('myid').id) <----- but this does not work

I know this works:

alert(docFragment.firstChild.id) <----- this does work, 开发者_JAVA百科but I was wondering if it is possible to reference it the other ways


No, it is not:

Simply creating an element and assigning an ID will not make the element accessible by getElementById. Instead one needs to insert the element first into the document tree with insertBefore or a similar method, probably into a hidden div.

And besides that, a DocumentFragment only implements methods of the Node interface and getElementById is not part of that.

There are no other ways to get an element by ID.

0

精彩评论

暂无评论...
验证码 换一张
取 消