获取元素在父级中的位置(索引)

Get the position(index) of an element in the parent

本文关键字:位置 索引 元素 获取      更新时间:2023-09-26

我想获取元素在其父元素中的位置。例如

<div>
<h2 class="one">A</h2>
<span>Something</span>
<h2 class="two">B</h2>
<h2 class="three">C</h2>
</div>

现在假设我得到一个h2.two$('h2.2')的参考;在一个事件中。我想要这个元素相对于div中其他h2的位置。在这种情况下,它是2。请不要告诉我我可以通过类名获得它,因为不会有这些类名。这只是为了解释。

注意:我想要它在h2列表中的位置,基本上是在$('h2.2').Pparent().children('h2')中,而不是所有元素中

function buildPath(element)
{
var Xpath,position=-1;
element=$(element);//Just in case;
Xpath=getTagName(element);
parent=element.parent();
console.log(parent.children(Xpath));
var position = element.siblings(Xpath).element.index(element);//I want the position here
Xpath="/"+Xpath+"["+position+"]";
    console.log(Xpath);
    console.log(getTagName(parent));
    if (getTagName(element)=='body')
    return Xpath;

 }
var $theH2 =  $('h2.two');
var index = $theH2.siblings("h2").andSelf().index($theH2);

下面是一个工作示例:

http://jsfiddle.net/Bm6Wd/

点击一个h2,它会提醒索引。