0

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"?

Mark Zucchini
  • 935
  • 6
  • 11

2 Answers2

1

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

(function() {
    window.addEventListener("load", function() {
        alert(document.getElementById('someElement'));
    }, false);
})();
Georgi Naumov
  • 3,890
  • 4
  • 33
  • 50
0

Your missing your closing curly brace }.

It should be

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

This will execute immediately so this needs to be placed somewhere appropriate to ensure the DOM has loaded. Make sure this script loads at the end of your HTML file, or include a check as Georgi Naumov has suggested, adding a listener to the window.load event will do the same thing.

Mark Walters
  • 10,729
  • 6
  • 31
  • 47