JavaScript JavaScript and the DOM Traversing the DOM Sibling Traversal

Sibling Traversal Challenge (assigning className to parentNode)

Hello,

I'm not quite sure what kind of answer this challenge is looking for. It's likely I've made an error somewhere, but I just cannot seem to find what I've done incorrectly.

Thanks!

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

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

2 Answers

Steven Parker
Steven Parker
127,593 Points

The instructions say "a class of highlight should be added to the paragraph element immediately preceding that button".

So it's not the button's parent element that should get the class, that would the list item ("li"). It should go on the paragraph right before the button.

Thanks! I guess I didn't read the instructions carefully enough.

I edited the variable to paragraphSibling and used .previousSibling, etc.

It worked.

Steven Parker
Steven Parker
127,593 Points

FYI: Since not all nodes are elements, "previousElementSibling" would be a better choice in general, but it's not necessary here since the two elements are adjacent.

Mark Warren
Mark Warren
11,387 Points

This worked for me:

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

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