JavaScript JavaScript and the DOM Traversing the DOM Sibling Traversal

charlie alton
seal-mask
.a{fill-rule:evenodd;}techdegree
charlie alton
Front End Web Development Techdegree Student 6,945 Points

I cant figure this out.

I dont remember them teaching me this in this course. I need help?

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

list.addEventListener('click', function(e) {
  if (e.target.tagName == 'BUTTON') {

  }
});
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>
Karla Walker
seal-mask
.a{fill-rule:evenodd;}techdegree
Karla Walker
Full Stack JavaScript Techdegree Student 8,618 Points

Hi charlie alton ! So the code challenge is asking you to add a class to the <p> tag, which is the previous sibling of the button you are clicking. The <button> element you are clicking and need to reference is equal to e.target. The challenge shares a link to the previousElementSibling property that you can use to get the <p> tag, I shared the link below:

https://developer.mozilla.org/en-US/docs/Web/API/Element/previousElementSibling

Once you have the <p> tag saved, you can use classList.add() to add the 'highlight' class to the <p> tag.

Here's a ink to the classList documentation in case you need a refresher on that:

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

I hope this helps! :)

1 Answer

Joseph Yhu
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Joseph Yhu
PHP Development Techdegree Graduate 46,902 Points
  1. Use the previousElementSibling property for e.target to select the <p> element that's beside each <button> element.
  2. Use the className property to set the classes of the selected <p> elements to highlight.