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>

3 Answers

Steven Parker
Steven Parker
140,485 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
140,485 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,753 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";  
  }
});
Luke Lai
Luke Lai
5,503 Points

May I ask why it would not work if I assign e.target.previousElementSibling to a new variable, then I change its class name ?

I tried on my own html on the computer, and it works the same way, so I guess it is about the exercise setting ?

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

list.addEventListener('click', function(e) {
  if (e.target.tagName == 'BUTTON') {
     let p = e.target.previousElementSibling;
     p.className = 'highlight';
  }
});
Steven Parker
Steven Parker
140,485 Points

It does work the same with the extra variable. But if you don't intend to use that variable again, why create it?

Jason Egipto
Jason Egipto
9,155 Points

Hey Luke Lai,

Im experiencing the same issue, following :)