-1

How do I get the level of depth of a list?

  • the list can be asymmetric
  • x number of "li" or "ul" nested

x number of li or ul

for example: A list of Level 2

<ul>
    <li>1
    </li>
    <li>2
        <ul>
            <li>2.1</li>
            <li>2.2</li>
            <li>2.3</li>
        </ul>
    </li>
    <li>3
    </li>
</ul>

A list of Level 3

<ul>
    <li>1
    </li>
    <li>2
        <ul>
            <li>2.1
                <ul>
                    <li>2.1.1</li>
                 </ul>
            </li>
            <li>2.2</li>
            <li>2.3</li>
        </ul>
    </li>
    <li>3
    </li>
</ul>
ch2o
  • 815
  • 2
  • 12
  • 29

1 Answers1

2

one way i came up with:

function getDepth(list){
     for(var depth=0; list.querySelector(Array(depth++ +3).join(list.tagName+" ")) ;  );
    return depth;
}

// example usage:
getDepth(  document.getElementsByTagName"ul")[0]  );

there may be better solutions, but this seems to work, and avoids the heavy iteration of a deepest child search, so it should be decently fast as well.

see fiddle to kick the tires: http://jsfiddle.net/nghea3ot/4/

i know this question's not getting a lot of love around here, but it's a great question with poor/na existing answers...

dandavis
  • 16,370
  • 5
  • 40
  • 36
  • thought I had a solution with jquery (selector or a method already) the solution and create a function to do it – ch2o Aug 11 '14 at 23:16