caramba
caramba

Reputation: 22480

Get first level li from ul

I thought this must be easy but couldn't find a way to get the first level <li> elements. I've tried like so:

var elements = document.querySelectorAll('ul > li');
console.log(elements);
<ul>
  <li>A</li>
  <li>B</li>
  <li>
    C
    <ul>
      <li>C1</li>
      <li>C2</li>
      <li>C3</li>
    </ul>
  </li>
  <li>D</li>
  <li>E</li>
</ul>

But that gives me all <li> elements including C1, C2 etc.

I would like to get only the elements

  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>

How to achieve that with vanilla javascript? Please no jQuery

Upvotes: 2

Views: 2031

Answers (1)

Bergi
Bergi

Reputation: 664297

Give the outer <ul> an identifier (or a class) and select them using ul#myId > li (or ul.myId > li) Or just specifiy that you don't mean the inner ul in any other way, e.g. body > ul > li.

Upvotes: 5

Related Questions