I have a set of divs that share a class name, but have no individual id. The order in which they show up in html is important and must be preserved. I need to be able to loop through the list of elements given by document.getElementsByClassName(className);
and give them each a unique id in the form "tile-1" "tile-2" etc
.
I thought something like this may work but I soon came to realise that this would not work:
const getTiles = document.getElementsByClassName(tileClass);
let n = 1;
for (e in getTiles){
let i = "tile-" + n;
e.setAttribute("id", i);
n++;
}
I was hoping it would be as easy as each element in the array having the setAttribute
applied to them but I was wrong.
Any suggestions?
2
Answers
As pointed out by @Barmar in the comments, I needed to use
of
instead ofin
in the for loop. Works as intended now.try that