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

Trying to addClassName to the previous Sibling Element and I can't get it to work.

Can someone please help me get through this problem??

app.js
var list = document.getElementsByTagName('ul')[0];

list.addEventListener('click', function(e) {
  for (let i = 0; i < list.length; i += 1){
    if (e.target.tagName == 'BUTTON') {
        let li = event.target.parentNode;
      let prevLi = li.previousElementSibling;
      let ul = li.parentNode;
      prevLi.className = 'highlight';
   }
  }
});
index.html
<!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

  • So the problem sets it up for you so that the target is a button. No need to make changes there.
  • The question refers to the immediately previous element, the paragraph. The most direct route would be to use the previousElementSibling method as they are in the same hierarchical level, they are siblings. If you like you could also go to the parent element and then the first child element of that parent as well.
  • Both should return the paragraph in question which you can then add the class in various ways, I used the setAttribute but there are others.
var list = document.getElementsByTagName('ul')[0];

list.addEventListener('click', function(e) {
  if (e.target.tagName == 'BUTTON') {
    e.target.previousElementSibling.setAttribute('class', 'highlight')
  }
});

Hope that helps.

Thank you I was making harder than it actually was.