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 trialYi Zhang
3,572 Pointsadding a class to a previous element sibling
I cannot understand where is the error.
const list = document.getElementsByTagName('ul')[0];
list.addEventListener('click', function(e) {
if (e.target.tagName == 'BUTTON') {
e.previousElementSibling.className = "highlight"
}
});
<!DOCTYPE html>
<html>
<head>
<title>JavaScript and the DOM</title>
</head>
<link rel="stylesheet" href="style.css" />
<body>
<section>
<h1>Making a Webpage Interactive</h1>
<p>Things to Learn</p>
<ul>
<li><p>Element Selection</p><button>Highlight</button></li>
<li><p>Events</p><button>Highlight</button></li>
<li><p>Event Listening</p><button>Highlight</button></li>
<li><p>DOM Traversal</p><button>Highlight</button></li>
</ul>
</section>
<script src="app.js"></script>
</body>
</html>
2 Answers
Justin Iezzi
18,199 PointsHi Yi Zhang,
Looks like you've simply forgotten to add the .target
property.
e.target.previousElementSibling.className = "highlight";
Nicholas Vogel
12,318 PointsIt's likely this line
e.previousElementSibling.className = "highlight"
You forgot the semi-colon at the end of "highlight". JS is that picky. You can also always check errors in the javascropt console.
miikis
44,957 PointsNot true, Nicholas. JavaScript has ASI (Automatic Semicolon Insertion); semicolons are rarely needed. In fact, the only time they're ever required — that I can think of off the top of my head — is before return statements that aren't preceded by a newline and IIFEs (Immediately Invoked Functional Expressions) that have been concatenated together.
Steven Parker
231,248 PointsYou also need semicolons between statements that are on the same one.