I have this markup
<div class="parent">
<div class="one"></div>
<div class="two"></div>
<div class="one"></div>
<div class="two"></div>
</div>
My question is: how to get "index" number of element with class two
. I'm not asking of regular index number of element in parent
div. I need to know that when i'm clicking at first element with class one
that next two
element have 0 index or it's first element in this list with class two
, and so on.
I've tried with index()
method and eq()
and always i have the real index number of this element in parent
div. I hope this is clear, thx for help.
I have this markup
<div class="parent">
<div class="one"></div>
<div class="two"></div>
<div class="one"></div>
<div class="two"></div>
</div>
My question is: how to get "index" number of element with class two
. I'm not asking of regular index number of element in parent
div. I need to know that when i'm clicking at first element with class one
that next two
element have 0 index or it's first element in this list with class two
, and so on.
I've tried with index()
method and eq()
and always i have the real index number of this element in parent
div. I hope this is clear, thx for help.
- It has to be in jQuery? – Typo Commented Aug 10, 2015 at 10:38
4 Answers
Reset to default 3You need to find the elements index in collection of element with sameclass:
$('.parent > div').click(function(){
var index;
if($(this).is('.one'))
index = $('.parent > .one').index(this);
else
index = $('.parent > .two').index(this);
});
This should be the faster way to get the index you are looking for.
Instead of retrieving all matches, it just counts the number of elements of the same class among previous leafs in your DOM.
Also, it allows having multiple <div class="parent">
and still work
$('.parent div').click(function() {
// Retrieve clicked element class (one, two)
var elClass = $(this).attr('class');
// Retrieve all previous elements that have the same class
// and count them
var prevElmts = $(this).prevAll('.' + elClass),
numPrevElements = prevElmts.length;
console.log(numPrevElements);
})
Using jquery you can find index of element which have same class name or tag name
$(".class_name").on("event_name", function() {
var index=($(this).index());
console.log('index : ',index);
});
This may work for you.
var p = $('.parent'),
current = p.filter('.two'),
index = p.index(current);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745278576a4620170.html
评论列表(0条)