jquery count siblings does not return correct result?

laukok picture laukok · May 11, 2012 · Viewed 14.1k times · Source

I want to count the sibling by classes,

html,

<div class="item-sibling">1</div>
<div class="item-holder"><div class="item-sibling">2</div></div>
<div class="item-holder"><div class="item-sibling">3</div></div>
<div class="item-holder"><div class="item-sibling">4</div></div>
<div class="item-holder"><div class="item-sibling">5</div></div>​

jquery,

var len = $('.item-sibling').siblings().css({background:'red'}).length;
alert(len);​​​​ // return 4

it does not include <div class="item-sibling">1</div>

how can I include it?

jsfiddle link

and if I change the html to,

<div class="item-sibling">0</div>
<div class="item-sibling">1</div>
<div class="item-holder"><div class="item-sibling">2</div></div>
<div class="item-holder"><div class="item-sibling">3</div></div>
<div class="item-holder"><div class="item-sibling">4</div></div>
<div class="item-holder"><div class="item-sibling">5</div></div>

I will get 6 this time. Strange!

EDIT,

<div class="group-a">
    <div class="item-sibling">1</div>
    <div class="item-holder"><div class="item-sibling">2</div></div>
    <div class="item-holder"><div class="item-sibling">3</div></div>
    <div class="item-holder"><div class="item-sibling">4</div></div>
    <div class="item-holder"><div class="item-sibling">5</div></div>​
</div>


<div class="group-b">
    <div class="item-sibling">1</div>
    <div class="item-holder"><div class="item-sibling">2</div></div>
    <div class="item-holder"><div class="item-sibling">3</div></div>
</div>

There are series of groups with the same class, and I want to count a targeted group's sibling dynamically for instance the first group.

Answer

jmar777 picture jmar777 · May 11, 2012

You can do

var len = $('.item-sibling').siblings().andSelf().css({background:'red'}).length;

Or...

var len = $('.item-sibling').parent().children().css({background:'red'}).length;

Edit: after reading your updated, I would suggest the following:

1) Add a generic "group" class to each group. E.g.,

<div class="group group-a">
    ...
</div>

2) Then take advantage of that class to find all "siblings":

var len = $('.item-sibling:first').closest('.group')
    .find('.item-sibling').css({background:'red'}).length;