admin管理员组文章数量:1221774
Given the following HTML:
<div class="component">
<div class="component">
<div class="component">
</div>
</div>
<div class="component">
<div class="somethingelse">
</div>
<div class="component">
</div>
<div class="component">
<input type="button" value="Get Path" onclick="showPath(this)" />
</div>
</div>
</div>
I'm trying to write the function showPath
so that it returns the index of the parent div
in relation to its siblings of class component
. So in the above sample, I would like the function to return 1
.
I've got this far, but it returns 2
; I don't know what to do to ignore the div
of class somethingelse
function showPath(element) {
var component = $(element).closest('ponent');
alert(component.index());
}
Given the following HTML:
<div class="component">
<div class="component">
<div class="component">
</div>
</div>
<div class="component">
<div class="somethingelse">
</div>
<div class="component">
</div>
<div class="component">
<input type="button" value="Get Path" onclick="showPath(this)" />
</div>
</div>
</div>
I'm trying to write the function showPath
so that it returns the index of the parent div
in relation to its siblings of class component
. So in the above sample, I would like the function to return 1
.
I've got this far, but it returns 2
; I don't know what to do to ignore the div
of class somethingelse
function showPath(element) {
var component = $(element).closest('.component');
alert(component.index());
}
Share
Improve this question
edited Dec 4, 2017 at 17:37
Nathan Arthur
9,0967 gold badges64 silver badges83 bronze badges
asked Mar 12, 2011 at 0:20
sandysandy
9131 gold badge11 silver badges25 bronze badges
3 Answers
Reset to default 9A quick and simple extension for jQ to turn this process into a method:
$.fn.getIndex = function(){
var index = $(this).parent().children().index( $(this) );
return index;
}
Run this on document.ready or wrap it in a function and run it that way (probably cleaner).
Usage is as simple as
var index_for_element = $('.thing-you-want-index-for').getIndex();
Try this(haven't tested):
function showPath(element) {
var component = $(element).closest('.component');
alert(component.parent().find(".component").index(component));
}
You can do this.
$('input').click(function() {
var component = $(this).closest('.component');
alert(component.parent().children(".component").index(component));
})
Check working example at http://jsfiddle.net/Qzk6A/2/
本文标签:
版权声明:本文标题:javascript - Using jQuery, how to find the index of an element amongst its siblings of a specified CSS class - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1739345206a2159126.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论