If you’ve used jQuery before, chances are you’ve also used the .siblings()
selector method. Selecting siblings of elements comes in handy in many applications, but what if instead of selecting siblings, you just wanted to count them?
Counting Siblings With jQuery
Counting the number of siblings an element has with jQuery is incredibly simple.
$("#someElementId").siblings().size()
We can also use an “if” statement to check if the element has any siblings at all.
if ($("#someElementId").siblings().size() > 0) { // then it has siblings } else { // it doesn't }
.size() doesn’t just work with the siblings selector, so interchange .siblings() with any of the other selectors jQuery offers.