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 JavaScript and the DOM (Retiring) Getting a Handle on the DOM Practice Selecting Elements

Russell Fincher
Russell Fincher
257 Points

How 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.

Russell Fincher
Russell Fincher
257 Points

Difficult to give someone credit for a best answer, I needed both of your advice to make this work. Thanks!

1 Answer

Steven Parker
Steven Parker
231,248 Points

This 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".

Russell Fincher
Russell Fincher
257 Points

Thanks, 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
Reuben Varzea
23,182 Points

Russell Fincher - I don't think getElementsByTagName() works with multiple tags. Try using querySelectorAll() instead.

Russell Fincher
Russell Fincher
257 Points

Thanks Reuben Varzea! I was unaware of that. This worked:

let navigationLinks = document.querySelectorAll('nav ul li a');

Steven Parker
Steven Parker
231,248 Points

It does, but just "nav a" is enough to uniquely identify the target elements.