Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

What is wrong with this JavaScript code?

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="css/normalize.css" rel="stylesheet">
    <title>A Clickable Button</title>
  </head>
  <body>
    <h1>A Clickable Button</h1>
    <button>Click Me!</button>
    <script src="js/script.js"></script>
  </body>
</html>

JavaScript:

const button = document.getElementsByTagName('button');
button.addEventListener('click', function() {
  alert('Yay! You clicked the button!');
});

Please can somebody tell me what I've done wrong?

1 Answer

Joel Bardsley
Joel Bardsley
31,258 Points

Hi Kieran, you're very close!

getElementsByTagName() returns a HTMLCollection of elements with the given tag name.

In your case, as you only have one button element in your code, you can use button[0] to access that (the first) button element, and apply the event listener as follows:

button[0].addEventListener('click', function() {
  alert('Yay! You clicked the button!');
});

Hope that clears things up for you.

Thanks, Joel -- just what I needed to know!