JavaScript - Assigning a class to an element based on an array

I am facing a challenge where I need to assign classes from an array to an element in sequential order. The issue is that once I reach the end of the array, I do not know how to loop back to the beginning and start over. Here is my current code:

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];  
    x++; 
}

Answer №1

One way to achieve this is by using modulo.

For example, if you want classes like blogspot red, you can use the following code:

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];
}

If you prefer classes like blogspotred, it becomes a bit more complex.
Since getElementsByClassName returns a node list and not an array, we need to handle it differently to avoid changes affecting other elements with different classes. Here's an approach you could take:

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];
}

Answer №2

To optimize your code, consider using modulo instead of directly accessing elements in an array. Instead of background[i], try backgrounds[i%3] where 3 represents the length of the array.

EDIT: In case you're unsure how modulo works, it returns the remainder after division. For example, 0%3 is 0, 1%3 is 1, 2%3 is 2, 3%3 is 0, and so on.

Answer №3

If you're not looking for a loop, but rather for a modulus solution, consider this code snippet:

const colors = ['green', 'purple', 'orange'];
const items = document.getElementsByClassName('article');
for (index=0; i<items.length; index++) {
    // It is more efficient to store the length of the array beforehand
    items[index].className += ' ' + colors[index % colors.length];
}

By using index % colors.length, you will get the remainder when dividing the iterator by the array's length. For example, 0 -> 0, 1 -> 1, 2 -> 2, 3 -> 0, and so forth.

Correction based on feedback: This approach dynamically uses the array's length instead of hard-coding 3.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging JavaScript within a Polymer component

I have an object made with polymer: <newfolder-element id="newfolderelement" popupStyle="width: 362px; height: 100px;"> <span class="title">Create a new folder</span> <input type="text" class="ginput" style="width: 350px; padd ...

What is the best way to use ajax to send a specific input value to a database from a pool of multiple input values

Welcome everyone! I'm diving into the world of creating a simple inventory ordering site, but am facing a roadblock with a particular issue: Imagine you have a certain number (n) of items in your inventory. Based on this number, I want to run a &apos ...

After updating Angular Material, the alert dialogs are now transforming into a large dark region

Recently, I encountered an issue while attempting to upgrade my old version of angular-material (v0.9.0) to a newer one. The reason behind this upgrade was the necessity to utilize the new htmlContent for an alert using $mdDialog. However, after replacing ...

The jQuery dropdown selection for only displaying the month and year is not functioning properly when using the select

Currently, I am utilizing a datepicker with only the month and year as options to select from using dropdowns. However, when I apply the following CSS to disable the days of the datepicker, it ends up affecting all datepickers in my JSP file. 1. Is there ...

Webpack does not support d3-tip in its current configuration

I'm having some trouble getting d3-tip to work with webpack while using TypeScript. Whenever I try to trigger mouseover events, I get an error saying "Uncaught TypeError: Cannot read property 'target' of null". This issue arises because th ...

Employing ajax with dynamically created buttons in PHP

I'm struggling to figure out what to search for in this situation. I've tried piecing together code from others, but it's just not working for me. My ajax function successfully retrieves data from a database through a php page and displays ...

Loading an Angular app causes Chrome devtools to freeze

Currently, I am facing some unusual behavior in my rather large Angular (1.5) application. When I have Chrome DevTools open while loading the app, the CPU usage of that particular tab shoots up to 100%, causing the app to take a minute or more to load. Add ...

Unable to get Mongoose's Required field to work in conjunction with Enum validation

Encountering issues with Mongoose Required true and Enum validation when using updateone await MonthlyTarget.updateOne({website: req.body.website, year: req.body.year, month: req.body.month}, req.body, {upsert: true}); Model 'use strict'; import ...

Clicking on the button has no effect whatsoever

I'm currently dealing with a button on my webpage that seems to be causing me some trouble: <script> function changeMap() { container.setMap(oMap); } </script> <button onClick="changeMap"> Click here </button> Upon inspe ...

Issues have been reported regarding the paramMap item consistently returning null when working with Angular 8 routing

I am encountering an issue with Angular 8 where I am trying to fetch some parameters or data from the route but consistently getting empty values. The component resides within a lazy-loaded module called 'message'. app-routing.module.ts: ... { ...

Difficulty with Bootstrap 4 mobile navbar dropdown feature

<div class="baslik baslik1 baslik2 "> <nav class="navbar bg-light navbar-light navbar-expand-sm sticky-top "> <a href="./index.html" class="navbar-brand"><img src="img/512x512logo.png" ...

The JSON response from Rails containing multiple lines is not being parsed accurately

I am currently working on a Rails application with a json response using show.js.erb. { "opening": "<%= @frame.opening %>", "closing": "<%= @frame.closing %>"} An issue I encountered is that when @frame.opening contains multiple lines, jQuer ...

Activate a dropdown menu following the selection of a date on a calendar input using vue.js

What I need to do is have two select fields, one for 'days' and the other for 'hours'. When a day is selected, the user should then be able to choose between two available time slots. If they choose day two, the available time slots sh ...

Is requesting transclusion in an Angular directive necessary?

An issue has cropped up below and I'm struggling to figure out the reason behind it. Any suggestions? html, <button ng-click="loadForm()">Load Directive Form</button> <div data-my-form></div> angular, app.directive(&apos ...

Converting objects to arrays in AngularJS and Ionic: A simple guide

In the scenario where I have an object structured like this: {first: "asdasd", second: "asdas", third: "dasdas", four: "sdasa"}, my objective is to convert this object into an array. if(values){ var first=values.first; var second=values.second; var ...

Tips for saving the web address and breaking down each word

Hello, I am familiar with how to store URL parameters using the following JavaScript code. However, I am wondering if there is a way to store each word that comes after a slash in a URL. For example, let's consider the URL: http://localhost:9000/Data ...

Unraveling and interpreting all incoming requests to my Node.js application

Looking for a simple method to identify and decipher all encoded characters in every URL received by my Node.js application? Is it possible to achieve this using a middleware that can retrieve and decode symbols such as & ? ...

prismjs plugin for highlighting code displays code in a horizontal format

If you're looking for a way to showcase source code on your website with highlighted syntax, prismjs.com may be just what you need. It offers a similar style to monokai... However, I've encountered an issue where the plugin displays my code in a ...

A step-by-step guide on making a web API request to propublica.org using an Angular service

Currently, I am attempting to extract data from propublica.org's congress api using an Angular 8 service. Despite being new to making Http calls to an external web api, I am facing challenges in comprehending the documentation available at this link: ...