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, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With