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!

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) Traversing the DOM Sibling Traversal

Code 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>
        <title>JavaScript and the DOM</title>
    <link rel="stylesheet" href="style.css" />
            <h1>Making a Webpage Interactive</h1>
            <p>Things to Learn</p>
                <li><p>Element Selection</p><button>Highlight</button></li>
                <li><p>Event Listening</p><button>Highlight</button></li>
                <li><p>DOM Traversal</p><button>Highlight</button></li>
        <script src="app.js"></script>

2 Answers

Neil McPartlin
Neil McPartlin
14,662 Points

Hi Moe. I see 2 issues.

  1. 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.

  2. 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
dragos busuioc
24,908 Points

prevButton.classList.add('highlight' )instead prevButton.className = 'highlight';

I got the same error: "There was an error with your code: TypeError: 'null' is not an object (evaluating 'prevButton.classList')"