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 trialLeila Mahmoudi
5,037 Pointsprevious sibling
Can someone walk me through this, please? I'm having a hard time understanding what happening here how could I add a class of highlight to a <p> element that's an immediate previous sibling of the button is clicked.
var list = document.getElementsByTagName('ul')[0];
list.addEventListener('click', function(e) {
if (e.target.tagName == 'BUTTON') {
if(e.target.previousElementSibling.tagName && e.target.previousElementSibling.tagName === "P"){
e.target.previousElementSibling.classList.add('highlighted');
}}
}
);
<!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>
1 Answer
Steven Parker
231,268 PointsYou're close, here's a few hints:
- the instructions say to add a class of 'highlight' to the paragraph (not 'highlightβed')
- the conditional expression has a spurious term in it (before and including the
&&
) - the instructions say you can expect the previous sibling to be a paragraph, you don't need to test it at all
Jason Larson
8,361 PointsJason Larson
8,361 PointsActually, the instructions don't say anything about what to expect for the previous element's sibling. In this challenge, you can omit the testing for the 'p' tag and it will work because the html has only p elements as immediate previous siblings for the buttons, but that doesn't mean that it would always work that way, so given the instructions "to add a class of
highlight
to a<p>
element that's an immediate previous sibling of the button being clicked", I would also have done it the way Leila did (without the other issues mentioned, of course).Steven Parker
231,268 PointsSteven Parker
231,268 PointsThe instructions say to add a class "to a <p> element that's an immediate previous sibling...". So they're telling you that the previous sibling (of this element, the button) will be a paragraph.