JavaScript JavaScript and the DOM Traversing the DOM Using parentNode to Traverse Up the DOM

does anyone know how to select nested ul/ol list by using getElementByTag name then count how many nested ul/ol inside?

<ul>
        <li>Item:
            <ol><!--level 1-->
                <li>Point:
                    <div>
                        <ul><!--level 2-->
                            <li>elem1</li>
                        </ul>
                    </div>
                </li>
            </ol>
        </li>
        <li>elem2</li>
    </ul>



    <ul>
        <li>simple list1</li>
    </ul>

    <ul>
    </ul>

2 Answers

Steven Parker
Steven Parker
171,904 Points

Sure, you nearly described the process yourself in the question.

var ul = document.getElementsByClassName("ul")[0];
var nested = ul.getElementsByTagName("OL").length
           + ul.getElementsByTagName("UL").length;
alert(`There are ${nested} nested lists inside the outer one.`);

sorry I didn't explain properly. What I meant to say was - I'm trying to select the "UL" tag try to count the length of nested ul/ol inside. It should return 2.

I've tried to loop through the "li" but not too sure how? hope that make sense.

Steven Parker
Steven Parker
171,904 Points

That's exactly what the code shown does. It selects the outer "ul" and then counts the nested lists inside, putting the count into the variable "nested". The alert then confirms that value is 2.

Steven Parker thank you for such a simple solution, but just a quick question. Don't you need to loop through the "<li>" tag first and check what is inside? e.g dom traversing etc?

Thank you in advance.

Steven Parker
Steven Parker
171,904 Points

You don't need a program loop because getElementsByTagName handles finding all the elements for you.