JavaScript JavaScript and the DOM Traversing the DOM Sibling Traversal

Brian Thomas
Brian Thomas
10,688 Points

Not sure how this code is not adding the class name highlight to the p tags. Can someone help explain?

.

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

list.addEventListener('click', function(e) {
  if (e.target.tagName == 'BUTTON') {
    let ul = e.target.parentNode;
    let p = e.target.previousElementSibling;
    p.addClass('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

John McGarvey
John McGarvey
8,820 Points

Brian, I think the problem is that the addClass() method comes from jQuery. I don't think it exists in vanilla javascript. I think you can do p.className = 'highlight' , and I think that would be accepted as an answer to the quiz, but of course it has the unfortunate side effect that if the paragraph had a class value, it would be replaced, not added to.

I am kind of new to javascript, so this answer is provisional.

Adam Yarber
Adam Yarber
7,373 Points

Brian, I can confirm that replacing p.AddClass('highlight') with p.className = 'highlight'; will be correct for this code challenge!