getElementById Where Element is dynamically created at runtime

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


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


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

Here obj return null value.

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

To add an element using JavaScript, you need to do 2 things.

  1. Create the element

    var element = document.createElement(tagName);

  2. Add it to the dom

    document.body.insertBefore(selector, element);



More info here: MDN

If a DOM node is dynamically created, then there’s no need EVER to find it again with document.getElementById().

By creating the node in the right way, you can keep a reference to it as a javascript variable, which can be used anywhere within scope.

Read More:   What is the Javascript equivalent of Python's get method for dictionaries

For example:

window.onload = function(){
    var myDiv = document.createElement('div');

    //and now a function that's called in response to some future event
    function whatever(){

Note: The inner function (called at some point(s) future) has access to the myDiv variable because the outer function forms a “closure”, within which variables are kept alive and accessible, even though the outer function has completed and returned.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts