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.
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 .
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.
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.
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'); };
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