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 trialJake Kobs
9,215 PointsaddEventListener() - Problem with button clicks setting background color
Everything in my code looks fine to me, but when I click on any of the buttons, the body color of the webpage doesn't change. Here's my JavaScript code:
const body = document.getElementsByTagName('body');
const button = document.getElementsByTagName("button");
document.addEventListener("click", (event) => {
console.log(event.target);
});
button.addEventListener("click", (event) => {
if(event.target.tagName == "BUTTON"){
if(event.target.className == "red"){
body.style.background = "red";
}
if(event.target.className == "blue"){
body.style.background = "blue";
}
if(event.target.className == "orange"){
body.style.background = "orange";
}
if(event.target.className == "yellow"){
body.style.background = "yellow";
}
}
});
HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Practice JS</title>
<link rel="stylesheet" href="cssPrac.css">
</head>
<body>
<div class="container">
<header>
<h1>JavaScript Practice</h1>
<div class="bList">
<button class="red">Color to red</button>
<button class="blue">Color to blue</button>
<button class="orange">Color to orange</button>
<button class="yellow">Color to yellow</button>
</div>
</header>
</div>
<script src="jsPrac.js"></script>
</body>
</html>
1 Answer
Steven Parker
231,007 PointsThe "addEventListner" method is only available on individual elements, but "button" is assigned to an HTMLCollection returned by the selector method.
Similarly, "body" is also assigned to an HTMLCollection, but only individual elements have a "style" property.
Jake Kobs
9,215 PointsJake Kobs
9,215 PointsThank you very much, Steven! All I had to do was change .getElementsByTagName to .querySelector and create class names for the body and pointed to the parent of the buttons class name.
Steven Parker
231,007 PointsSteven Parker
231,007 PointsThat's a good fix, and another one would be to add indexing (
...[0]
) to the collection selector to get just the first element from it.