Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve document elements - Document ready

Tags:

javascript

Could somebody please explain why this button does not work? The error in my console indicates that var button = document.getElementById('next'); is returning 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 your help

like image 647
Kane Avatar asked Mar 20 '23 23:03

Kane


2 Answers

Run the JS after the HTML has loaded. When you call the JS in the head, the button doesn't exist yet, it's rendered after the JS is called.

This will work:

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

</head>
<body>
    <button id="next">Say hi</button>
    <script type="text/javascript">
        ...
    </script>
</body>
</html>
like image 142
Reeno Avatar answered Apr 02 '23 14:04

Reeno


At the time the script runs you have no element with the id next.

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

e.g.

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

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

addEventListener('load', setUpButton);
like image 45
Quentin Avatar answered Apr 02 '23 15:04

Quentin