Count amount of LI within a UL

2

Show amount of LI within a UL.

I have the following HTML:

<ul class="rodapeUlCat margin-top-25">
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
    </ul>
    <div class="rodapeCat">Outras Categorias (16)</div>

What I want to do is say Other Categories (16) in "16", it shows the amount of li contained within ul .

I made a Jquery:

$( ".rodapeUlCat" ).append( $( "<li>" ) );
var n = $( "li" ).length;
$( ".rodapeCat" ).text( + n + );

I wonder what I did wrong. length counts the elements, right? Maybe the error is append , but I do not know what to put in place.

    
asked by anonymous 07.10.2014 / 16:45

3 answers

8

First, be careful:

Instead of $( "li" ).length use $( ".rodapeUlCat li" ).length , to count the <li> of just the desired div.

It may even be the case that you use a id separated in each block if you have several by the screen, or find the nearest element via JQuery before counting.

In this way, the code looks like this:

var n = $( ".rodapeUlCat li" ).length;
$( ".rodapeCat" ).text( "Outras categorias( " + n + " )" );

I made a JS Fiddle that randomly generates the amount of <li> s to demonstrate better .

    
07.10.2014 / 17:02
2

You can use .size() to do this action.

var total = $(".rodapeUlCat li").size();
$(".rodapeCat").text(total);

See example

    
07.10.2014 / 16:55
0

Is there any way to only count divs visible using the above code?

for example in the code below:

var total = $(".rodapeUlCat li").size();
    $(".rodapeCat").text(total);
.esconde{
  display:none;
  }
<ul class="rodapeUlCat margin-top-25">
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
        <li class="esconde><h3><a href="/paginaSYS">tituloMenuSYS</a></h3></li>
    </ul>
    <div class="rodapeCat">Outras Categorias (16)</div>
    
25.10.2016 / 21:51