Reputation: 5160
How do I get the parent element's index value in relation to the document, of the clicked child, $(this)
, element?
<html>
<body>
<header>
<div class="gallery">
<div class="controls">
<button class="next"></button>
<button class="previous"></button>
</div>
</div>
</header>
<section>
<section>
<article>
<div class="gallery">
<div class="controls">
<button class="next"></button>
<button class="previous"></button>
</div>
</div>
<div class="gallery">
<div class="controls">
<button class="next"></button>
<button class="previous"></button>
</div>
</div>
</article>
</section>
</section>
</body>
</html>
In this HTML it is possible to declare a gallery at any place you like within the body. So I need an “intelligent” selector to solve the problem.
$('.controls button').click(function() {
var hope = $(this).parents('.gallery').index();
alert(hope);
}
Scenario
Click on a button of the second gallery in this document:
1
Upvotes: 3
Views: 982
Reputation: 3517
Try this:
$('.gallery').index( $(this).parents('.gallery') );
.index()
is finding the index of the passed element in the group of elements that it is applied to.
Take a look at my working jsFiddle example.
source(s)
Upvotes: 5
Reputation: 5271
When you call index(), it gives you the position relative to the collection of elements you have selected, in this case,
$(this).parents('.gallery')
Instead, you want it relative to the galleries in the entire document, so you need:
$('.gallery').index($(this).parents('.gallery'))
Upvotes: 4