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 Selecting Multiple Elements

Ken S.
Ken S.
3,838 Points

In Javascript, how to select all li within a ul with a class? No jQuery.

I can solve the challenge, but I am unsatisfied with my solution. Googled for a while with no luck on the specific solution I'm looking for.

Want to select li elements within a ul with a class ONLY. In the challenge you can pass just by selecting all li because there is no other ul.

How do you select all li within a ul with a class? I've tried along these lines:

document.querySelectorAll('ul.className li');

1 Answer

Kieran Barker
Kieran Barker
15,028 Points

The solution you posted would work! I just tested this myself!

HTML:

<ul class="list">
  <li>Within a Class (1)</li>
  <li>Within a Class (2)</li>
  <li>Within a Class (3)</li>
</ul>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

JavaScript:

const listItems = document.querySelectorAll('.list li');
for (let i = 0; i < listItems.length; i++) {
  alert (listItems[i].textContent);
}

I made it alert the text content of each list item within the <ul class="list">. Only those ones, not the other <ul> without a class! Try it yourself :)

Ken S.
Ken S.
3,838 Points

Thanks! I did actually end up taking the opportunity to test all sorts of combos for quite a while to get a better understanding. As for my particular issue, I recall it being some kind of silly mistake like trying to select class when it was a tag, or a typo, or something silly like that.