2

On a particular item, how can I know what the current child count is?

for example:

<div id="parent">
  <img id="lorem" />
  <img id="ipsum" />
  <img id="dolor" />
  <img id="sit" />
  <img id="amet" />
</div>

how can I know $('#sit') is # 4 of its siblings ? I could iterate over all children and count but this seams very slow especially because I need to update it quite often and because there are hundreds of siblings and I only need to target the last 5 siblings

A workaround to my solution would be to be able to target the last 5 children's independently. Any idea how?

PSL
  • 123,204
  • 21
  • 253
  • 243
Vincent Duprez
  • 3,772
  • 8
  • 36
  • 76
  • 1
    FYI, `.index` internally probably does nothing else but iterate over the siblings/children. There is no DOM property which contains the index of the element. You can only get it by traversing the DOM. – Felix Kling Nov 19 '13 at 23:05

1 Answers1

5

You can use .index()

$('#sit').index() // will give you the index (zero based) with respective to its siblings.

And if you want to find last 5 children of the parent, try:

 $('#parent').children(':nth-last-child(-n + 5)');
PSL
  • 123,204
  • 21
  • 253
  • 243