Use getElementById for the newly created DOM object before it is inserted into the document - HOW?

The getElementById method cannot be used if the DOM element is not attached to the document. By what method or mechanism can I access and modify the DOM element before attaching it to the document?

I have a large DOM element and I want to get part of it. I would classically use getElementById , but the DOM element is not attached to the document.

 var element = document.createElement("div"); element.id = 'testqq'; var el = document.getElementById('testqq'); // el will be null! 

source: https://developer.mozilla.org/en/dom/document.getelementbyid

I am looking for an answer that does not use jQuery. I like jQuery, but this is not an option for my current problem.

+4
source share
2 answers

Well, you already have a link to it using the element variable.

But I bet you mean that you want something inside. If it is right, you can use getElementsByTagName('*') , then iterate over the returned collection by checking the ID property until yours is found.

 var div = document.createElement('div'); div.innerHTML = '<p>yo</p><div><span id="tester">hi</span></div>'; var all = div.getElementsByTagName('*'); // search for element where ID is "tester" for (var i = 0, len = all.length; i < len; i++) { if (all[i].id === 'tester') { var result = all[i]; break; } } alert( result.id ); 

Before you try the loop, you can check if querySelectorAll is querySelectorAll in the browser and use that if it is.

 if( div.querySelectorAll ) { var result = div.querySelectorAll('#tester'); } else { // Do the loop with getElementsByTagName() } 
+4
source

The document.createElement function returns a new element object, but this element does not exist in the DOM until you enter it .

The document object has no memories of the elements you asked to create, so when you call document.getElementById('testqq') , it absolutely does not know what you are looking for.

In your example, you already have a link to the element. Why do you need to request a document?

0
source

All Articles