0

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?

Tutti Frutti
  • 1
  • 1
  • 4

2 Answers2

1

try that

let i = 1;
document.querySelectorAll('.post').forEach(el => {
  el.id = 'title-' + i;
  i++
})
<div class="post">
</div>
<div class="post">
</div>
<div class="post">
</div>
<div class="post">
</div>
pier farrugia
  • 1,520
  • 2
  • 2
  • 9
0

As pointed out by @Barmar in the comments, I needed to use of instead of in in the for loop. Works as intended now.

Tutti Frutti
  • 1
  • 1
  • 4