Search code examples
javascriptgetelementsbyclassname

JavaScript: assign unique ID to elements containing a certain class


So I have this HTML code:

  <p style="margin-bottom: 5px"><span id="" class="stars-container stars-custom">★★★★★</span></p>

basically I want to assign a unique id to each instance of this element, so first element id="1", second element id="2" etc.

I was thinking of using getElementsByClassName to identify them and grab the class name, but how do I assign and a unique id?? I'm pretty new to JS so I don't get how the loop will look like.


Solution

  • This will handle. You basically select all of the p elements with the classes you indicate, loop over them and set the id for each of them to the index of the loop variable.

    I could not use a foreach loop as it's not usable on HTMLCollections

    const paragraphs = document.getElementsByClassName('stars-container stars-custom');
    
    for (let i = 0; i < paragraphs.length; i++) paragraphs[i].setAttribute('id', i + 1);