Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById Where Element is dynamically created at runtime

Tags:

I have created an object at runtime by using innerHTML tag, now I want to access this element by using getElementById, when I accessed the element its return NULL value. Kindly suggest me any direction so that I can acheive this,

Here is the following code hint which I am using

In HTML

<div id="web"> <object id="test"></object> </div> 

In JS

document.getElementById("web").innerHTML="<object id='test2'></object>"; . . var obj = document.getElementById("test2"); 

Here obj return null value.

like image 776
Siddiqui Avatar asked Mar 28 '12 07:03

Siddiqui


People also ask

How do you add an event listener after an element was created dynamically?

To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .

How do you create new element dynamically?

New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.

What is dynamically created?

A dynamic object is created using a "new" operator that returns a pointer to the newly constructed object and is destructed by a "delete" operator. A pointer variable is used to hold the pointer to the object that is returned by the "new" operator.


1 Answers

Did you assign an id to the freshly created element? Did you insert the element into the document tree (using appendChild or insertBefore)? As long as the element is not inserted into the DOM, you can't retrieve it using document.getElementById.

Example of element creation:

var myDiv = document.createElement('div'); myDiv.id = 'myDiv'; document.body.appendChild(myDiv); document.getElementById('myDiv').innerHTML = 'this should have worked...'; 

[edit] Given the later supplied code, a third question emerges: is your script located at the bottom of your html page (right before the closing </body> tag)? If it's in the header of the document, your scripting may be running before the document tree is completely rendered. If your script has to be in the header of the document, you could use a load handler to run it after rendering of the document:

window.onload = function(){   document.getElementById("web").innerHTML='<object id="test2"></object>';   // [...]   var obj = document.getElementById('test2'); }; 
like image 128
KooiInc Avatar answered Oct 01 '22 03:10

KooiInc