Reputation: 2737
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
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
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();
});
Upvotes: 3
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