Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript and the DOM (Retiring) 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
221,451 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
221,451 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
221,451 Points

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