简体   繁体   中英

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

给外部<ul>一个标识符(或类)并使用ul#myId > li (或ul.myId > li )选择它们或者只是指明你不是指任何其他方式的内部ul,例如body > ul > li

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM