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 trial

JavaScript JavaScript and the DOM (Retiring) Traversing the DOM Sibling Traversal

Vasanth Baskaran
Vasanth Baskaran
4,333 Points

One or more of the buttons do not affect their sibling paragraphs.

I know my code is not selecting the previous element of the Button, but it is selecting the previous element of 'ul'. Could anyone please help on this ? Thanks !

const list = document.getElementsByTagName('ul')[0];

list.addEventListener('click', function(e) {
  if (e.target.tagName == 'BUTTON') {
    let prev = e.target.previousElementSibling;
    prev.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>

1 Answer

Steven Parker
Steven Parker
230,233 Points

Your selector is selecting the correct element, but the extra spaces being added to the class name are throwing off the result.

I's OK to just replace the class name for this exercise, but if you would rather add a new class in a way that won't affect others already there (a good practice!) use the "add" method of the "classList" property:

Vasanth Baskaran
Vasanth Baskaran
4,333 Points

Thanks Parker,

There was no Class added to P element in given code. So instead of using the following code

prev.className += " highlight ";

I have removed the + sign and it worked.

prev.className = " highlight ";

Cheers and Happy Coding !!!

Steven Parker
Steven Parker
230,233 Points

It would still be better without the spaces in the name. :point_right: prev.className = "highlight";