admin管理员组文章数量:1418426
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);
本文标签:
版权声明:本文标题:javascript - How to get index, position number of element with certain class with jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745278575a2651315.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论