admin管理员组

文章数量:1352158

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 .

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 .

Share Improve this question asked Apr 16, 2016 at 5:52 S.M_EmamianS.M_Emamian 17.4k40 gold badges154 silver badges273 bronze badges 1
  • What is interesting here is I tried to find a duplicate because I was sure there was one - The duplicate questions are not as specific as this one so the answers would need some work do be as definitive as @Ori_Drori's – mplungjan Commented Apr 16, 2016 at 6:06
Add a ment  | 

4 Answers 4

Reset to default 6

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;

Use child selector with class:

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

alert(vote_selected);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

alert($('#star-rating li.selected').length)//use selector li.selected
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>

Use selector ex. li.classname

Check this,

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

本文标签: javascriptCounting the number of elements with the same class jqueryStack Overflow