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 JavaScript and the DOM (Retiring) Getting a Handle on the DOM Select a Page Element By Its ID

Geoff Hignett
Geoff Hignett
8,187 Points

MyHeading works. Changing to MyButton does not work :(

// I don't understand how this is possible???

const myHeading = document.getElementById("myHeading");

myHeading.addEventListener ("click", () => { myHeading.style.color = "red"; });

// This works perfectly.

const myHeading = document.getElementById("myHeading"); const myButton = document.getElementById("myButton");

myButton.addEventListener ("click", () => { myHeading.style.color = "red"; });

// This does not work. All I have done is switch myHeading with myButton as per the vid

<!DOCTYPE html> <html> <head> <title>JavaScript and the DOM</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <h1 id="myHeading">JavaScript and the DOM</h1> <p>Making a web page interactive</p> <script src="app.js"></script> <button id="myButton">Click Here</button> </body> </html>

2 Answers

Adam Pengh
Adam Pengh
29,881 Points

Looking at your HTML structure, you have the <button id="myButton> element after the JS. HTML and JavaScript are parsed as the DOM is read. So the JS document.getElementById("myButton") is searching for an element that hasn't been created in the DOM yet. There are 2 fixes.

  1. Move the button element above the JS.

  2. Wait until the load event to parse the JS. For example, wait until the onload event, then run the JS. This also has performance benefits as the visual aspects of the page can be loaded before the functional JS is run.

window.onload = function() {
  const myHeading = document.getElementById("myHeading");
  myHeading.addEventListener ("click", () => { myHeading.style.color = "red"; });

  const myHeading = document.getElementById("myHeading"); const myButton = document.getElementById("myButton");
  myButton.addEventListener ("click", () => { myHeading.style.color = "red"; });
}