skip to Main Content

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


  1. Chosen as BEST ANSWER

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


  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search