Nisarg
Nisarg

Reputation: 3262

Jquery : find length of mixed list

This is example list :

<ul>
    <li>Item:
        <ol>
            <li>Point:
                <div>
                    <ul>
                        <li>elem1</li>
                    </ul>
                </div>
            </li>
        </ol>
    </li>
    <li>elem2</li>
</ul>
<ul>
    <li>Point:
        <div>
            <ul>
                <li>elem1</li>
            </ul>
        </div>
    </li>
</ul>
<ul>
    <li>simple list1</li>
</ul>

I have a code to find depth from unordered list :

var n = 0

$('ul').each(function(i){ 
    if (($(this).parents('ul').length + 1) > n) { n = $(this).parents('ul').length + 1; }
});

But what to do if more than one list and which are mixed list ?

EDIT : Here mixed list means ul list and ol list.

Upvotes: 0

Views: 492

Answers (1)

Mosh Feu
Mosh Feu

Reputation: 29277

The key is to add ol to the selector of the check.

var n = 0

$('ul, ol').each(function(i){ 
    if (($(this).parents('ul, ol').length + 1) > n) { n = $(this).parents('ul, ol').length + 1; }
});

$('#result').html(n);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>Item:
        <ol>
            <li>Point:
                <div>
                    <ul>
                        <li>
                          elem1
                          <ol>
                            <li>elem1_1</li>  
                          </ol>
                      </li>
                    </ul>
                </div>
            </li>
        </ol>
    </li>
    <li>elem2</li>
</ul>
<ul>
    <li>Point:
        <div>
            <ul>
                <li>elem1</li>
            </ul>
        </div>
    </li>
</ul>
<ul>
    <li>simple list1</li>
</ul>

<hr />

<div id="result"></div>

Upvotes: 1

Related Questions