Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

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

like image 601
bryan sammon Avatar asked Dec 06 '25 19:12

bryan sammon


1 Answers

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.

like image 61
Felix Kling Avatar answered Dec 08 '25 07:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!