getElementById Where Element is dynamically created at runtime

后端 未结 3 746
一向
一向 2020-11-30 08:33

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. Kin

相关标签:
3条回答
  • 2020-11-30 09:18

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

    or

      document.getElementByID(selector).appendChild(element);
    

    More info here: MDN

    0 讨论(0)
  • 2020-11-30 09:21

    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');
    };
    
    0 讨论(0)
  • 2020-11-30 09:26

    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.

    For example:

    window.onload = function(){
        var myDiv = document.createElement('div');
        document.body.appendChild(myDiv);
    
        //and now a function that's called in response to some future event
        function whatever(){
            ...
            myDiv.style.color = 'red';
            ...
        }
    };
    

    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.

    0 讨论(0)
提交回复
热议问题