Search code examples
javascripthtmlcounthtml-listsremovechild

Count how many UL Elements there are in a Div with Javascript?


I am dynamically adding UL elements to a DIV element. I would like to be able to count how many UL elements there are inside the DIV so that once all the ULs are removed dynamically I can delete the DIV that they are contained in.

<div id="000">

<ul id="000-1">
<li>Stuff</li>
<li>Stuff</li>
</ul>

<ul id="000-2">
<li>Stuff</li>
<li>Stuff</li>
</ul>

</div>

Is there a simple Javascript solution that counts the amount of ULs so that I can do something like this.. ?

if(ulcount == 0){

var remove = document.getElementById("000");
remove.innerHTML = '';
results.parentNode.removeChild("000");

}

Thanks.


Solution

  • @Cheeso's answer is a good pure-JS solution. But, if you're using jQuery, the process can be made simpler.

    jQuery('div#000').children('ul').length;
    

    The above code will return the number of child ul elements of the div#000.

    To update the count when you add elements dynamically, you will have to create a function and call it to update the number whenever a change occurs:

    function countUls() {jQuery('div#000').children('ul').length;}
    

    Bind that to an event so that it will be called when you want to update the number.