在纯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.