What is the best way to retrieve classes from arrays and apply styling to them using javascript?

Imagine having 3 unique classes: alpha, beta, and gamma. Each class contains 3 individual div elements like so:

<div class="alpha"></div>
<div class="alpha"></div>
<div class="alpha"></div>

<div class="beta"></div>
<div class="beta"></div>
<div class="beta"></div>

<div class="gamma"></div>
<div class="gamma"></div>
<div class="gamma"></div>

Now, assign variables to each class:

var a = document.getElementsByClassName("alpha");
var b = document.getElementsByClassName("beta");
var c = document.getElementsByClassName("gamma");

Combine them all into an array named elements:

var elements = [a, b, c];

If the goal is to change the text color of all div elements within the classes alpha, beta, and gamma, how can this be achieved without multiple loops like below:

function changeColor() {
  var j;
  for (j = 0; j < a.length; j++) {
    a[j].style.color = "blue";
  }

for (j = 0; j < b.length; j++) {
        b[j].style.color = "blue";
      }

for (j = 0; j < c.length; j++) {
        c[j].style.color = "blue";
      }
}

It would be great to use only one loop to go through the elements array and change the text color of all divs within each class dynamically.

Answer №1

For adding them to the nums array, it is recommended to utilize the concat method (and also convert the NodeLists into arrays)

var nums = Array.from(_1).concat(Array.from(_2)).concat(Array.from(_3));

Alternatively, you can make use of the spread operator

var nums = [..._1,..._2,..._3];

Afterwards, proceed with

function textColor() {
  nums.forEach(node => node.style.color = 'red');
}

Answer №2

To simplify your nums array, you can use the following approach:

let flattenedNums = [].concat.apply([], nums)

After flattening the array, you can iterate through it:

for (let j = 0; j < flattenedNums.length; j++) {
    flattenedNums[j].style.color = "blue";
}

Answer №3

A simple solution would be to use the following code:

$(".one, .two, .three").prop("style","color: red;");

Alternatively, you could create a second class for all nine div elements.

Answer №4

To make things even simpler, apply the same style to all divs like this:

divs=document.querySelectorAll('.one, .two, .three');
divs.forEach(function(el) {
el.style.color='red';
})

divs=document.querySelectorAll('.one, .two, .three');
divs.forEach(function(el) {
el.style.color='red';
})
<div class="one">1</div>
<div class="one">2</div>
<div class="one">3</div>

<div class="6">
skip
</div>

<div class="two">4</div>
<div class="two">5</div>
<div class="two">6</div>

<div class="three">7</div>
<div class="three">8</div>
<div class="three">9</div>

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

Change the position of a Div by clicking on a different Div using JQuery for custom movements

I have successfully managed to slide the div left/right based on the answers below, but I am encountering some issues with the top div. Here are the specific changes I am looking to make: 1. Make both brown lines thinner without affecting the animations. ...

Implementing pagination for images offers a user-friendly browsing experience

My friend and I are in the process of creating a website that displays images from two directories in chronological order. The image name serves as a timestamp, and we generate a JSON object using PHP with the code below: <?php $files = array(); $dir ...

What is the best way to include the toast component in my button?

I am brand new to working with Next.js and React. I have a button in my project that triggers an external JavaScript file (query.js). After the script finishes executing, I would like to display a toast notification indicating whether it was successful or ...

Having issues with Firefox rendering JavaScript and CSS correctly

I'm trying to figure out if it's the row class from Bootstrap that's causing issues, or if there's a problem with my JS/CSS not loading properly in Firefox. It seems to be working fine in Chrome and Safari. Any ideas on what could be go ...

Tips for preserving images while browsing a website built with Angular single-page application

Utilizing Angular's router for component navigation has been beneficial, but I am facing an issue with component reloads when going back. To address the problem of content reloading from the server, I have implemented a solution where the content arra ...

Creating an HTML page that mimics the appearance of a PDF document across different screen sizes

I am working on a mock brochure/magazine/resume single page site and utilized bootstrap's container-fluid. The layout appears as follows - body div - container-fluid div - container-fluid row col-7 col-1 col Each column contains ...

Rearrange the order of items in the fancybox gallery

Typically, fancybox displays items in the gallery based on the order they are added in the HTML code. Is there a way to customize the order of items when they are opened in the popup, while keeping the original order when displayed on the page? The solut ...

Encountering difficulty in retrieving data from an unidentified JSON array using Javascript

Exploring the realm of Javascript and JSON, I find myself faced with a challenge - accessing values in an unnamed JSON array. Unfortunately, as this is not my JSON file, renaming the array is out of the question. Here's a snippet of the JSON Code: [ ...

What is the best way to update a specific element within a web page?

My current implementation involves utilizing this code snippet within a functional component : return ( <div style={{ height: "700px", overflow: "auto" }}> <InfiniteScroll pageStart={0} loadMore={Fet ...

What is the best way to make a scrollable div with top and bottom padding without adding extra elements inside?

I have created a fiddle to demonstrate my question. Essentially, I am looking to create a scrollable container with padding at the top and bottom that remains visible during scrolling, ensuring there is always a consistent distance from the edge to the con ...

How can you stop a document event listener from triggering?

Utilizing document.addEventListener('touchstart', this.onDocument); allows me to recognize when a user taps outside of an element. However, within my button click handler, the following code is present: toggleItemActive(e) { e.stopPropa ...

The Mongoose connection status is consistently showing as 0

Utilizing nodejs and mongoose to establish a connection with my MongoDB Database. I am attempting to check the connection state, specifically if it is connected or not. I am using mongoose.connection.readyState to achieve this. The connection seems to be ...

Attempting to align the fixed banner in the middle of my blog

I have spent hours combing through code after code on this site, trying to center my fixed banner without success. I am feeling frustrated and in need of some assistance. Here is the CSS snippet I have been working with: .heading { position:fixed; ...

Designing tables and image galleries using HTML, CSS, and jQuery: A guide

How can I easily transform tabular data into thumbnails with the click of a button? I need a 2-view system that switches between table and thumbnail views without including image thumbnails. I welcome any creative suggestions! :) Examples: ...

Instructions on extracting a random element from an array and continue removing elements from the array until it is completely empty

I am attempting to utilize either jquery or javascript to remove a random item from an array until it is empty. Each time I remove an item, I want to log it to the console. My goal is to create elements with random images from the specified array until all ...

A step-by-step guide on initializing and setting a cookie value with expiration

Below is the code I have added. Can someone please help me locate the bug? Here is the code snippet: $_SESSION['browser'] = session_id(); setcookie($expire, $_SESSION['browser'], time() + (60 * 1000), "/"); echo "Value is: " . $_COO ...

What is the best way to send an array of objects to a Node.js server?

What is the method for sending an array of objects with user data to the server for verification? I am attempting to pass orderform data to a server for validation and then display it on a different page after redirection. const addProductsToServer = (ev ...

How can you pick the element that is nearest to the top of a window?

My goal is to have a fixed list of page sections on the side that highlights the link of the section you're currently viewing as you scroll through the page. This is the code I've come up with: $(document).scroll(function(){ $allSections = $(&a ...

Updating NPM packages versions is currently restricted

I'm in the process of creating a Next.JS application using create-next-app. However, I've noticed that in the package.json file it lists the following dependencies: "eslint": "8.43.0", "eslint-config-next": &quo ...

The tilesloaded event in google.maps.event.addListener is unexpectedly failing to trigger

Today, while testing popover messages on my cordova/ionic app, I compiled the app and noticed that the maps weren't loading. Instead, only my custom "Loading map..." spinning icon kept showing. Upon investigating further, I found that var setMap = n ...