Pages

Set unique id in every element of the same class

Today I face a problem to catch class elements. It changes location when appearing pop up image. So catching specific class element by class index position is not working in this case. Then, I find out a solution. And, I am going to share with you.

Here is initial code something like this:

<div class='magicthumb'>
    content-a here
</div>
<div class='magicthumb'>
    content-b here
</div>
<div class='magicthumb'>
    content-c here
</div>

I need content-a is active when I click .button-a class button. But when appearing pop up image active .magicthumb break the order. So in this case document.getElementsByClassName("magicthumb")[0] is not working. I use the js code to solve the problem.

var magicThumb = document.getElementsByClassName("magicthumb");
var magicLength = magicThumb.length;
for(var i = 1; i <= magicLength; i++) {
    magicThumb[i].setAttribute("id","magicthumb-" + i);
}

Then I have no problem to catch the specific content because they have unique id as well.

<div id="magicthumb-1" class='magicthumb'>
    content-a here
</div>
<div id="magicthumb-2" class='magicthumb'>
    content-b here
</div>
<div id="magicthumb-3" class='magicthumb'>
    content-c here
</div>