S.M_Emamian S.M_Emamian - 7 months ago 12
Javascript Question

Counting the number of elements with the same class- jquery

I have an

ul
element. now I would like to know how many of
li
's have
selected
class .

<ul class="icon-list icon-list-inline star-rating" id="star-rating">

<li class="selected"></li>
<li class=""></li>
<li class=""></li>
<li class=""></li>
<li class=""></li>
</ul>


var vote_selected = $('#star-rating ... ???').length;


it must return 1 .

Answer

Try this :-

var vote_selected = $('#star-rating li[class="selected"]').length;

DEMO

Or (as li is immediate descendents of #star-rating you can use >).

var vote_selected = $('#star-rating > li[class="selected"]').length;

Or

var vote_selected = $('#star-rating > .selected').length;
Comments