Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Vanilla JavaScript Navigation is Not Working

Does anyone know why this Javascript is not working? I know how to do it in jQuery but I want to use vanilla JavaScript. The goal is to make a border-bottom on the active link. Thank you!

<body>

<style> .active { border-bottom: 1px solid white; } </style>

<header> <h1>RACHEL MILLER</h1> <nav> <ul> <li><a href="#" class="active">WORK</a></li> <li><a href="#">DETAILS</a></li> <li><a href="#">CONTACT</a></li> </ul> </nav> </header>

<script> var nav = document.querySelector('nav a');

nav.addEventListener("click", function () { alert("working"); nav.classList.remove('active'); this.classList.add("active"); }); </script>

</body> </html>

</body>

1 Answer

document.querySelector() will only return the first element that matches, in this case the first anchor of the nav. If you want the handler on all the links you'll need to use document.querySelectorAll() instead and iterate through the list of elements.

Thank you, super helpful :)