Reputation: 33
I want to get an index of clicked element
var $inputs = $("input");
$inputs.click(function() {
console.log($(this).index())
});
it works well for following structure
div>(input+input+input)
But I need it for this case
div>input
div>input
div>input
Inputs are not siblings and I get the same index for each element. What is the simplest way to get that index?
Upvotes: 3
Views: 74
Reputation: 115222
Check index within the jQuery element collection by providing element as an argument and apply index()
method on element collection.
var $inputs = $("input");
$inputs.click(function() {
console.log($inputs.index(this));
});
var $inputs = $("input");
$inputs.click(function() {
console.log($inputs.index(this));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input>
<div>
<input>
</div>
</div>
<div>
<input>
</div>
<div>
<input>
</div>
<div>
<input>
</div>
Upvotes: 3
Reputation: 6904
$(this).closest('div').index()
https://api.jquery.com/closest/
Upvotes: 0
Reputation: 2709
You can use .parent()
, for example:
$(this).parent().index();
divs
with inputs must be wrapped in div
Upvotes: 0