javascriptgetelementbyidself-executing-function

(function() { document.getElementById() == null; })();


Why self-executing anonymous function can't get access to DOM elements. Why such example does not work.

(function() {
    alert(document.getElementById('someElement'));
)();

Why alert will show "null"?


Solution

  • Just execute it on DOM load.You can use script defer attribute also.

    (function() {
        window.addEventListener("load", function() {
            alert(document.getElementById('someElement'));
        }, false);
    })();