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 trialSergio Cruz
15,550 Points.querySelector("a") not working. I wrote listItems.querySelector("a"); but it doesnt go through
It shows an error that says: TypeError: 'undefined' is not a function. Evaluating: listItems.querySelector("a")
//Select the naviagation
var navigation = document.getElementById("navigation");
//Select all listItems from the navigation
var listItems = navigation.children;
//When a navigation link is pressed
var linkListener = function() {
console.log("Listener is clicked!");
}
var bindEventsToLinks = function(listItem) {
//Select the anchor
var anchor = listItems.querySelector("a");
//Bind the linkListener to the anchor element (a)
anchor.onclick = linkListener;
}
for(var i = 0; i < listItems.length ; i++) {
bindEventsToLinks(listItems[i]);
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<ul id="navigation">
<li>
<a href="#home">Home</a>
</li>
<li>
<a href="#about">About</a>
</li>
<li>
<a href="#contact">Contact</a>
</li>
</ul>
<p>A few of my favourite things:</p>
<ul>
<li>
Rain drops on roses
</li>
<li>
Whiskers on kittens
</li>
<li>
Brown paper packages wrapped up with string
</li>
</ul>
<script src="app.js"></script>
</body>
</html>
3 Answers
Andrew Robinson
16,372 PointsHad to edit this answer, I assumed querySelector could only be used on a single node, turns out you are using 'listItem' not 'listItems' in your bindEventsToLinks function parameters.
Sascha Bratton
3,671 PointsLooks like you accidentally tried to run querySelector
against the global listItems
when you meant to run it against the listItem
parameter in your bindEventsToLink
function.
Sergio Cruz
15,550 Pointslol yeah it was just a typo. Thanks for helping!