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 trialRussell Fincher
257 PointsHow do I select list items when the page has multiple lists?
Trying to use a selector to select the items in a list, but there are multiple lists on the page. The list items I'm trying to select are within the <nav> tags.
1 Answer
Steven Parker
231,271 PointsThis might be a good place for a descendant selector.
That's where you separate the terms with a space, and the items on the right are selected only if they are inside the item on the left. For example, the links (a) inside a "nav" would be selected by: "nav a"
.
Reuben Varzea
23,182 PointsWhat Steven Parker said. :)
Russell Fincher
257 PointsThanks, Steven! That sounds sensible, but I'm still not able to make this work. So here's a snippet of the HTML including the nav element:
<body>
<header>
<a href="index.html" id="logo">
<h1>Nick Pettit</h1>
<h2>Designer</h2>
</a>
<nav>
<ul>
<li><a href="index.html" class="selected">Portfolio</a></li>
<li><a href="about.html">About</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</nav>
</header>
<div id="wrapper">
And here is my attempt to select them in javascript:
let navigationLinks = document.getElementsByTagName('nav a');
I also tried:
let navigationLinks = document.getElementsByTagName('nav ul li');
let navigationLinks = document.getElementsByTagName('nav ul li a');
let navigationLinks = document.getElementsByTagName('nav li');
None of these return the three links.
Reuben Varzea
23,182 PointsRussell Fincher - I don't think getElementsByTagName() works with multiple tags. Try using querySelectorAll() instead.
Russell Fincher
257 PointsThanks Reuben Varzea! I was unaware of that. This worked:
let navigationLinks = document.querySelectorAll('nav ul li a');
Steven Parker
231,271 PointsIt does, but just "nav a" is enough to uniquely identify the target elements.
Russell Fincher
257 PointsRussell Fincher
257 PointsDifficult to give someone credit for a best answer, I needed both of your advice to make this work. Thanks!