How to get elements of a document - Ready for the document

Can someone explain why this button does not work? An error in my console indicates that it var button = document.getElementById('next');returns null.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <script>
        ...
    </script>
</head>
<body>
    <button id="next">Say hi</button>
</body>
</html>

JavaScript:

var button = document.getElementById('next');
function sayHi(){
    alert('Hi there');
}

button.addEventListener('click',sayHi,false);

thanks for the help

+4
source share
4 answers

When you run the script, you do not have an element with id next.

  • Move the element <script>so that it appears after the element with this id or
  • Wrap the contents of the script in a function and bind this function as an event handler for the event that will be executed after the element exists

eg.

function sayHi(){
    alert('Hi there');
}

function setUpButton() {
    var button = document.getElementById('next');
    button.addEventListener('click',sayHi,false);
}

addEventListener('load', setUpButton);
+2
source

JS , HTML. JS , , JS.

:

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>
    <button id="next">Say hi</button>
    <script type="text/javascript">
        ...
    </script>
</body>
</html>
+4

script , DOM (Document Object Model) .
  <script> <head> , onreadystatechange ( ):

DOM - <head>

<script>
document.onreadystatechange = function () { 
    if(document.readyState === "interactive") { // use "complete" as a 'load' alternative
         /* (DOM is now read and ready to be manipulated) your code here */
    }
}​
</script>
</head>

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/readystatechange
https://developer.mozilla.org/en/docs/web/api/document/readystate


DOM - </body>

IE8 < JS </body>:

<!-- Your page elements before the script tag -->

<script>
   /* (DOM is now read and ready to be manipulated) your code here */
</script>
</body>
+1

script , , . script i.e

<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="next">Say hi</button>
<script>
    ...
</script>
</body>

0

All Articles