1
<html>
<style>
#myA {
    height: 300;
    width: 300;
    background: green;
}
</style>
<body>
<script language="JavaScript">

document.getElementById('myA').onmousedown = function() {
    var a = document.getElementById('myA');
    console.log(a);
}
</script>
<div id="myA"></div>
</body>
</html>

Please, why does not the code above work? When I want to write console.log, I get nothing, null value.

Andrej Tk
  • 47
  • 1
  • 9
  • See also [Why does jQuery or a DOM method such as `getElementById` not find the element?](http://stackoverflow.com/q/14028959/1048572) – Bergi Feb 13 '13 at 19:26

3 Answers3

3

When your script runs, the myA element doesn't yet exist. Either:

  • move your script to the end of the page
  • put it in a named function that you call from another script block at the end of the page
  • put your code in window.onload
  • use jQuery to run your code after the DOM is built, via $().
RichieHindle
  • 244,085
  • 44
  • 340
  • 385
0

You have to write script below that div. Because div is not loaded yet. Or you can write function and this function call when the document is ready.

Tom
  • 642
  • 4
  • 13
0

Wrap your code in a function and attach it to window.onload event, like this:

window.onload = function(e) {
    document.getElementById('myA').onmousedown = function() {
        var a = document.getElementById('myA');
        console.log(a);
    };
};

As the other guys said, it happens because you're trying to attach an event to an element that is not loaded yet.

Thiago Pontes
  • 416
  • 5
  • 16