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