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 trialUnsubscribed User
3,436 PointsCode is working for me but not in the challenge
Upon testing the code in the browser, the class name "highlight" is being added to the previous button upon "click" event. But I'm getting this error when I check the work on teamtreehouse: "There was an error with your code: TypeError: 'null' is not an object (evaluating 'prevButton.className = 'highlight'')"
Can you explain what I did wrong?
const list = document.getElementsByTagName('ul')[0];
list.addEventListener('click', function(e) {
if (e.target.tagName == 'BUTTON') {
let li = e.target.parentNode;
let prevButton = li.previousElementSibling;
prevButton.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
Neil McPartlin
14,662 PointsHi Moe. I see 2 issues.
Your code is actually setting the className of the 'li' previous to the 'li' containing the button. So this is why you are getting 'null' when you click the top button.
But if you carefully read the challenge it says...
When any one of the buttons is clicked, a class of highlight should be added to the paragraph element immediately preceding that button inside the parent list item element
So you actually need to be applying 'highlight' to the paragraph that contains the text, immediately previous to the button, within the same li. So this is one solution...
let button = event.target;
button.previousElementSibling.className = "highlight";
dragos busuioc
24,908 PointsprevButton.classList.add('highlight' )instead prevButton.className = 'highlight';
Unsubscribed User
3,436 PointsI got the same error: "There was an error with your code: TypeError: 'null' is not an object (evaluating 'prevButton.classList')"