What is the best way to create a repetitive pattern using a for loop in Javascript?

I want to create a repeating pattern to color the background, but once i exceeds colors.length, the background color stops changing because, for example, colors[3] does not exist. I need colors[i] to start back at 0 until the first loop is complete.

const arr = document.getElementById('collection');
const colors = ['#FFC6C6', '#A4BDFF', '#F9F9F9'];

for (let i = 0; i < arr.children.length; i++) {
    arr.children[i].style.background = colors[i];
}

Answer №1

Explore the concept of modulo

const list = document.getElementById('items');
const shades = ['#FFC6C6', '#A4BDFF', '#F9F9F9'];

for (let j = 0; j < list.children.length; j++) {
    list.children[j].style.backgroundColor = shades[j % shades.length];
}

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

What is the best way to draw a rectangle outline in Vue.js without the need for any additional packages?

I have been attempting to craft a rectangle outline using vueJS, but so far I have not had much success. I am hoping to achieve this using only CSS, but despite my efforts, I have not been able to find a solution. My goal is to create something similar to ...

Attempting to execute a synchronous delete operation in Angular 6 upon the browser closing event, specifically the beforeunload or unload event

Is there a way to update a flag in the database using a service call (Delete method) when the user closes the browser? I have tried detecting browser close actions using the onbeforeunload and onunload events, but asynchronous calls do not consistently wor ...

How can I pan/move the camera in Three.js using mouse movement without the need to click?

I am currently working on panning the camera around my scene using the mouse. I have successfully implemented this feature using TrackballControls by click and dragging. function init(){ camera = new THREE.PerspectiveCamera(45,window.innerWidth / windo ...

Tips for implementing a handler on a DOM element

$(document).ready(function(){ var ColorBars = document.getElementsByClassName("color-bar"); var number = 0; ColorBars[0].onclick = hideLine(0); function hideLine(index){ var charts = $("#line-container").highcharts(); v ...

Embed schema information into HTML tags using JavaScript

Is there a way to insert text, specifically schema data, into an HTML div tag using JavaScript? While I know how to modify existing values within a tag like class, href, and title, I am struggling to find a method to add something entirely new. Essentiall ...

The getElementById method in JavaScript can result in a null return value

Why is null returned by the getElementById method in JavaScript? <html> <head> <title>test_elementObject</title> <script language="JavaScript" type="text/javascript"> <!-- var input1 = document.getElementById ( " ...

Simple steps to update array key values in PHP

I am attempting to retrieve word counts from HTML documents stored in a specific folder. <?php $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('fulltext/course')); $fulltext_course_files = array(); foreach ($rii as $f) { ...

How to retrieve an unknown JSON key in Vue.js when using v-for loop?

I have developed a code analysis tool and I am looking to display my JSON data in a Vue table. The challenge is that I need the JSON key, which represents the package/file name of the directory whose data I want to showcase. Below is an excerpt of the JSO ...

The Node.js JSON string displays as "[object Object]" in the output

Front End // js / jquery var content = { info : 'this is info', extra : 'more info' } $.ajax({ type: 'POST', url: '/tosave', data: content }); Node // app.js app.post('/tosave', funct ...

The functionality of the dropdown does not seem to be working properly when the checkbox is

So, I have a simple task where if a checkbox is selected, a drop-down should appear. If the checkbox is unselected, the dropdown should not show up. However, it seems like there's an issue with my code. Here's a snippet below to give you an idea ...

Guide on transforming observable<User> to Observable<boolean> in Angular 4

As a newcomer in Angular and Mean Stack, I need help implementing the canActivate() method to restrict admin routes. In my service file, the checkAdmin method returns an observable of type "User", but the canActivate method's return type is an observa ...

Angular button will be disabled if the form control is empty

Is there a way to deactivate the search button when the text box is empty? I attempted to use the "disabled" attribute on the search button, but it didn't work. Here is my HTML code: <div class="col-md-5 pl-0"> <div class="in ...

The text color remains the same even after the method has returned a value

I have a vuex query that returns a list of books. I want to display each book with a specific color based on its status. I tried using a method to determine the color name for each book and bind it to the v-icon, but it's not working as expected - no ...

Populate Vue components dynamically without the need for additional frameworks like Nuxt in Vue3

My goal is to develop a checksheet application using Vue, where the tasks are specified in an excel file. ===== To start, task A needs to be completed. Followed by task B. and so on... ===== I am considering creating a CheckItem.vue component fo ...

Locating a record within a database that contains an objectId field linking to a separate collection

I have defined two collections in the following manner const BookSchema = new mongoose.Schema({ title: String, author: { type: mongoose.Object.Types.ObjectId, ref: "author" } }) const BookModel = mongoose.model(" ...

Eliminate any additional spacing within the pre/code tags

I am currently utilizing prism.js for code highlighting. I have encountered an issue where there are unnecessary white spaces at the top and bottom of my output. You can view a live example here. <pre> <code class="language-css"> &lt ...

Highlight and trim lengthy text using React

Imagine I have a lengthy text: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo con ...

Discover the secret to smoothly scrolling to an element in ReactJs

Currently, I am in the process of constructing a Single Page Application (SPA) using React and one key functionality I need to implement is navigation that scrolls to specific sections on the page when clicked. This behavior is similar to how anchor tags w ...

Error: The array geocode-api encountered an IndexOutOfRangeException, indicating that the specified index was beyond the allowable bounds

I encountered an "index was outside the bounds of the array" exception while trying to retrieve the latitude value from a geocode request on this line of code: string strLat = myCoordenates.Results[0].Geometry.Location.Lat.ToString(); The purpose of this ...

Unable to modify an attribute due to TypeScript error: Type 'string' cannot be assigned to type 'never'

I am trying to modify an attribute of an object in TypeScript and React, but I keep encountering the following error message: Type 'string' is not assignable to type 'never'. This happens even though I have a check in place to verify th ...