Получить номер nth-child элемента в чистом JavaScript
Я делаю функцию для своего сайта, где я устанавливаю атрибут данных, который содержит номер nth-child этого элемента.
Моя 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 пока что:
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;
}
Как я могу получить номер nth-child элемента с чистым JavaScript (не jQuery), возможно ли это даже в JavaScript?