简体   繁体   中英

Javascript - Adding class to element from array

I would like to add classes to an element in order from an array. I have three different classes, and I am not sure how to loop back to the beginning of the array to start over when I get to the end of the array of classes. Here is what I have so far:

var backgrounds = ["gray", "red", "blue"];
var elements = document.getElementsByClassName("blogpost");
var x = 0;
for (i = 0; i < elements.length; i++) {
    elements[i].classname += backgrounds[i];  //This is where I do not know how to add the elements in order
    x++; //This will get to the end of the array, how do I loop back to the beginning of the array after hitting the last element?
}

Just use modulo.

If you want classes like blogspot red then go with:

var backgrounds = ["gray", "red", "blue"];
var elements = document.getElementsByClassName("blogpost");
var len = backgrounds.length;
for (i = 0; i < elements.length; i++) {
    elements[i].className += ' ' + backgrounds[i%len];
}

It gets a little more interesting if you want classes like blogspotred , though.
getElementsByClassName doesn't return an array, but instead a node list, which will change once you start changing the classes (keep in mind, blogspotred doesn't fall under blogspot anymore). In that case you can, for example, do the following:

var backgrounds = ["gray", "red", "blue"];
var elements = Array.prototype.slice.call(document.getElementsByClassName("blogpost"));
var len = backgrounds.length;
for (i = 0; i < elements.length; i++) {
    elements[i].className += backgrounds[i%len];
}

You need to use mod. instead of using backgrounds[i] , use backgrounds[i%3] where 3 is the length of the array

EDIT: in case you aren't aware of what that does, it gives the remainder. so first 0%3 is 0, then 1%3 is 1, 2%3 is 2, 3%3 is 0, 4%3 is 1, so on and so forth

What you're looking for is not a loop, but a modulus:

var backgrounds = ['gray', 'red', 'blue'];
var elements = document.getElementsByClassName('blogpost');
for (i=0; i<elements.length; i++) {
    // the following could be slightly optimized by storing the value to
    // backgrounds.length before the loop starts
    elements[i].className += ' ' + backgrounds[i%backgrounds.length];
}

Using i%3 gives you the remainder of your i iterator divided by 3. So, 0 -> 0, 1 -> 1, 2 -> 2, 3 -> 0, and so on.

Edit: Added correction from comments, and used superior choice to dynamically mod on the length of the array rather than static 3 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM