Javascript - document.createDocumentFragment() - referencing a element by ID
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 withinsertBeforeor 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.
加载中,请稍侯......
精彩评论