在纯JavaScript中获取元素的第n个子数 [英] Get an element's nth-child number in pure JavaScript

查看:1518
本文介绍了在纯JavaScript中获取元素的第n个子数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a function for my site where I set a data attribute which contains the nth-child number of that element.

我的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>

我的JavaScript到目前为止:

My JavaScript so far:

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;
}

如何获得纯JavaScript的元素的第n个子元素不是jQuery),这在JavaScript中是可能的吗?

How can I get the nth-child number of an element with pure JavaScript (not jQuery), is this even possible in JavaScript?

推荐答案

如果是1,2等,那么数字只是i + 1 ...

If 1, 2, etc, then the number is simply i+1...

如果one,two等,那么你需要获取元素内部的文本,然后可能使用Regexp来解析它并获得所需的值。

If "one", "two", etc, then you need to get the text inside the element, then probably use a Regexp to parse it and get the value you want.

这篇关于在纯JavaScript中获取元素的第n个子数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆