Looking for elements with specific depth in JavaScript

I need to write a function in pure JavaScript witn no framework to get all specific tags, but only from first level under parent.

For example: I need to call some function on first <ul> and get all <li> from first level of it (<li> with text 1.2 and <li> with text 2.1)

<div id="sideNavigation">
    <ul>
       <li class=" act open  "> 
          1.2
          <ul>
             <li class="  ">
                1.2
                <ul>
                   <li class="  ">
                      1.3
                      <ul>
                         <li class="  ">1.4</li>
                      </ul>
                   </li>
                </ul>
             </li>
          </ul>
       </li>
       <li class="  ">
          2.1
          <ul>
             <li class="  ">2.2.1</li>
             <li class="  ">2.2.2</li>
             <li class="  ">2.2.3</li>
          </ul>
       </li>
    </ul>
</div>

I’ve been trying to do it like this:

var allLi = document.getElementById("sideNavigation").getElementsByTagName("li"); 

but it returns all <li> in this div not only first level <li>. Do you have any quick method to solve my problem or do I have to implement a new function to detect depth of nodes

73 thoughts on “Looking for elements with specific depth in JavaScript”

Leave a Comment