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

Arpana Roy
Arpana Roy
2,028 Points

addListener event doesnt work for button

app.js

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

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

index.html

<!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> <script src="app.js"></script>

<p>Making a web page interactive</p>
<input type="text" id = "myInputText">
<button id="myButton">Change color</button>

</body> </html>

whats wrong with this code? it doesnt work. It works with just myHeading but not with myButton.

What do you want to happen? Looks like you are making the heading color change when you click the button. Are you expecting something else?

3 Answers

Arpana Roy
Arpana Roy
2,028 Points

Thank you Steven , I will keep that in mind.

Regards, Arpana

Steven Parker
Steven Parker
229,644 Points

I'm not sure what you mean, the code appears to be intended to change the color of the heading to red when you click on the button. It seems to accomplish this when tested.

When you say "It doesn't work", what result were you expecting?

Arpana Roy
Arpana Roy
2,028 Points

Actually , when I clicked on button , the heading dint change the color. I made a mistake in the html code where I added the script before creating the button. Thats why it was not considering the button. I corrected it. It works. Thank you !!

Steven Parker
Steven Parker
229,644 Points

I overlooked that because I tested the code in a sandbox tool that includes the script without using the HTML to load it.

To facilitate the most accurate analyses, make a snapshot of your workspace and post the link to it here. That also eliminates the need to be sure pasted code is formatted.

I made the same mistake, too. "I made a mistake in the html code where I added the script before creating the button."