Marco
Marco

Reputation: 2737

How many elements in the list, the index of the element clicked

Consider the following markup

<ul id="thumbs">
    <li><a href=""><img class="thumb" src=""></a></li>
    <li><a href=""><img class="thumb" src=""></a></li>
    <li><a href=""><img class="thumb" src=""></a></li>
</ul>

When i click on an img with a class 'thumb', i want the following:

How many list items in the ul list
The index of the list item where the clicked img belongs to

$('img.thumb').click(function(e) {
    // how many elements in the list 'thumbs'

    // the index of the <li> where the img clicked belong to
});

Upvotes: 1

Views: 46

Answers (3)

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

Try

$('img.thumb').click(function(e) {
  $("#thumbs li").length;
  $(this).closest("li").index();
});

You can use either closest("li") or parents("li") for getting the parent li purpose. You can find the index using index() method. and length() for getting the count

Upvotes: 1

Felix
Felix

Reputation: 38112

You can use length to get the total number of list items as well as .closest() and .index() to get index of the closest ancestor li of clicked image:

$('img.thumb').click(function(e) {
    // how many elements in the list 'thumbs'
    var length = $('#thumbs li').length;

    // the index of the <li> where the img clicked belong to
    var index = $(this).closest('li').index();
});

Fiddle Demo

Upvotes: 3

Milind Anantwar
Milind Anantwar

Reputation: 82251

Try this:

  $('img.thumb').click(function(e) {
   // how many elements in the list 'thumbs'
     alert($('#thumbs li').length);
   // the index of the <li> where the img clicked belong to
     alert($(this).closest('li').index());
});

Upvotes: 1

Related Questions