I am making a function for my site where I set a data attribute which contains the nth-child number of that element.
My HTML markup:
<
Simply incrementing the index linearly will only work if all the elements matching that class name are the only element children of the same parent, with no other elements that could interfere with :nth-child(), as shown exactly in the given markup. See this answer for an explanation on how other elements might interfere. Also review the Selectors spec on :nth-child().
One way to achieve this that is more foolproof is to loop through the child nodes of each element's parent node, incrementing a counter for each child node that is an element node (since :nth-child() only counts element nodes):
var selector = document.getElementsByClassName('hardware');
for (var i = 0; i < selector.length; i++) {
var element = selector[i];
var child = element.parentNode.firstChild;
var index = 0;
while (true) {
if (child.nodeType === Node.ELEMENT_NODE) {
index++;
}
if (child === element || !child.nextSibling) {
break;
}
child = child.nextSibling;
}
element.dataset.number = index;
}
JSFiddle demo
Note that this will apply the correct index regardless of where the given element is in the DOM:
If a particular section.hardware element is the first and only child of a different section, it will be assigned the correct index of 1.
If a .hardware element is the second child of its parent, even if it is the only one with that class (i.e. it follows some other element without the class), it will be assigned the correct index of 2.