Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialjoeboo2529
9,805 Pointsdoes 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
231,271 PointsSure, 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.`);
joeboo2529
9,805 PointsSteven 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
231,271 PointsYou don't need a program loop because getElementsByTagName handles finding all the elements for you.
joeboo2529
9,805 Pointsjoeboo2529
9,805 Pointssorry 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
231,271 PointsSteven Parker
231,271 PointsThat'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.