在纯JavaScript中获取元素的第n个子编号

Sak*_*rda 16 html javascript css-selectors

我正在为我的网站创建一个函数,我在其中设置了一个数据属性,其中包含该元素的第n个子编号.

我的HTML标记:

<html>
<body>
    <section class="hardware">some text, nth-child is one</section>
    <section class="hardware">some text, nth-child is two</section>
    <section class="hardware">some text, nth-child is three</section>
    <section class="hardware">some text, nth-child is four</section>
    <section class="hardware">some text, nth-child is five</section>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

到目前为止我的JavaScript:

var selector = document.getElementsByClassName('hardware');
for(var i = 0; i <= selector.length; i++) {
    var index = selector[i] //get the nth-child number here
    selector[i].dataset.number = index;
}
Run Code Online (Sandbox Code Playgroud)

如何使用纯JavaScript(而不是jQuery)获取元素的第n个子编号,这在JavaScript中是否可行?

jos*_*ley 5

在这里查看以前的答案.

它用

var i = 0;
while( (child = child.previousSibling) != null ) 
  i++;
//at the end i will contain the index.
Run Code Online (Sandbox Code Playgroud)


jca*_*ron 4

当你说“数字”时,你的意思是1、2等还是“一”、“二”等?

如果是 1、2 等等,那么这个数字就是 i+1...

如果是“一”、“二”等,那么您需要获取元素内的文本,然后可能使用正则表达式来解析它并获取您想要的值。

  • @Sake Salverda:只有当`getElementsByClassName()`返回的整个元素集包含在同一个父元素下并且没有其他子元素可能干扰`:nth-child()`时,这才“工作正常”。但如果你总是可以依赖这个假设,那么“i+1”确实就足够了。 (2认同)