JavaScript JavaScript and the DOM Traversing the DOM Sibling Traversal

Theresa Degler
Theresa Degler
Full Stack JavaScript Techdegree Student 7,499 Points

Need clarification on the challenge question

Apparently I don't understand what challenge is asking. I don't know why I get "One or more of the buttons do not affect their previous sibling paragraphs." when I click on Check Work button. I have coded it so that the first list item button doesn't affect anything because there is no immediate previous sibling, which is correct or else there will be an error in applying a class="highlight" to the nonexistent paragraph tag.

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

list.addEventListener('click', function(e) {
  if (e.target.tagName == 'BUTTON') {
    let li = e.target.parentNode;
    let prevLi = li.previousElementSibling;
    if (prevLi) {
      let p = prevLi.querySelector('p');
      p.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
171,120 Points

When the instructions say "a <p> element that's an immediate previous sibling of the button", they are just reminding you that the paragraph is the sibling of the button. The aren't talking about siblings of the list items.

There's a paragraph before every button, and that's what should be highlighted when you press the button.

Steven Parker
Steven Parker
171,120 Points

Theresa Degler — Glad to help. You can mark a question solved by choosing a "best answer".
And happy coding!