Reputation: 449
When i click on a element with a class named sections, i should get an alert showing what is it's class index, but it's showing a wrong number.
For example, if i click the first div
element with a class named sections
, javascript alert should say 1
, not 3
.
Is there a way to target class indexes with click()
using jQuery?
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>this is the title</title>
<style>
.sections {
width:200px;
padding:30px;
background:blue;
margin:20px;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div class="sections"></div>
<div class="sections"></div>
<div class="sections"></div>
<script src="jquery-1.8.2.min.js"></script>
<script src="script/script2.js"></script>
<script>
$('.sections').click(function() {
x = $(this).index();
alert(x);
});
</script>
</body>
</html>
Upvotes: 2
Views: 825
Reputation: 171690
index()
with no arguments gets index within all siblings.
You have 6 siblings....3 with the class and 3 without
Try
var $sections = $('.sections').click(function(){
var x = $sections.index(this);
alert(x);
});
Upvotes: 3
Reputation: 26
So, as you noticed, it's alerting it's index for itself among it's siblings in the DOM. (starting at 0)
If you want to get it's index among similar objects, you can use .index slightly differently.
$('.sections').click(function(){
x = $('.sections').index($(this));
alert(x);
});
This is still 0 based, so you can now expect that it will show 0 for the first item, then 1 and 2.
Upvotes: 1
Reputation: 22220
From the documentation:
If we omit the argument,
.index()
will return the position of the first element within the set of matched elements in relation to its siblings:
Your first .sections
element is in 4th position among its siblings, so it returns 3 (the first being 0).
You want to pass a selector or an element to index()
.
Upvotes: 0
Reputation: 6546
You are correct index()
, is used to find index of an element with respect to its siblings but correct way to use it in your code is.
$('.sections').click(function() {
var x = $('.sections').index(this);
alert(x);
});
Also, please note that it will start from 0
instead of 1
.
Upvotes: 1
Reputation: 55750
You need to pass in the selector
against which you want to index of ( if you want to get the index based on the specific class )
x = $('.sections').index(this);
$('.sections').click(function() {
x = $('.sections').index(this);
alert(x);
});
.sections {
width: 200px;
padding: 30px;
background: blue;
margin: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div></div>
<div></div>
<div></div>
<div class="sections"></div>
<div class="sections"></div>
<div class="sections"></div>
Upvotes: 1