getElementById Where Element is dynamically created at runtime

后端 未结 3 759
一向
一向 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: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.

提交回复
热议问题