Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.