What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names:

function rotateAllBoxes() {
  var boxes = document.getElementsByClassName("box");
  for (var i = 0; i < boxes.length; i++) {
    boxes[i].style.background = "rgba(55, 111, 172, 0.408)";
    boxes[i].style.transform = "rotateZ(180deg)";
  }
}
.wrap {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
}

.box {
  width: 50px;
  height: 50px;
  margin: 2px;
  transition: all 0.5s ease-in-out;
  background-color: rgba(111, 154, 201, 0.808);
}

<div class="wrap">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>
<button id="btn" onclick="rotateAllBoxes()">Rotate All Boxes</button>

Answer №1

To apply the "boxes" class to all of your boxes, you can easily target them using a query selector.

var elementsArray = document.querySelectorAll(".boxes");

Once you have selected all the elements with the "boxes" class, you can iterate through them using a for loop to customize their styles.

for (var i = 0; i < elementsArray.length; i++) {
   elementsArray[i].style.backgroundColor = "rgba(55, 111, 172, 0.408)";
   elementsArray[i].style.transform = "rotateZ(180deg)";
}

Answer №2

IDs are unique, meaning you cannot have more than 2 elements with the same ID. Instead of repeating IDs, you can target all the div elements inside the .wrap class using querySelectorAll or by selecting the div with their class names.

function home() {
// document.querySelectorAll(".box2, .box1") -> with the same class name
document.querySelectorAll(".wrap > div")
.forEach(box => {
box.style.background = "rgba(55, 111, 172, 0.408)";
box.style.webkitTransform = "rotateZ(180deg)";
});
}
.wrap {
display: grid;
grid-template-columns: repeat(8, 1fr);
}

.box1 {
background: rgba(111, 154, 201, 0.808);
width: 50px;
height: 50px;
margin: 2px;
transition-property: all;
transition-duration: 0.5s;
transition-timing-function: ease-in-out;
}

.box2 {
background: rgba(90, 134, 180, 0.808);
width: 50px;
height: 50px;
margin: 2px;
transition-property: all;
transition-duration: 0.5s;
transition-timing-function: ease-in-out;
}
<div class="wrap">
<div class="box2"></div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box1"></div>
</div>
<button id="btn" onclick="home()">submit</button>

-- Edit --

To revert the background color of the boxes back to their initial state after the animation is completed, you can add a transitionend event listener that triggers once the transition is complete and changes the background color back to its original value.

document.querySelector('#btn')
.addEventListener('click', function() {
document.querySelectorAll(".wrap > div")
.forEach(box => {
box.addEventListener('transitionend', function() {
this.style.background = this.classList.contains('box1') ? "rgba(111, 154, 201, 0.808)" : "rgba(90, 134, 180, 0.808)";
});

box.style.background = "rgba(55, 111, 172, 0.408)";
box.style.transform = "rotateZ(180deg)";
});
});
.wrap {
display: grid;
grid-template-columns: repeat(8, 1fr);
}

.box1 {
background: rgba(111, 154, 201, 0.808);
width: 50px;
height: 50px;
margin: 2px;
transition-property: all;
transition-duration: 0.5s;
transition-timing-function: ease-in-out;
}

.box2 {
background: rgba(90, 134, 180, 0.808);
width: 50px;
height: 50px;
margin: 2px;
transition-property: all;
transition-duration: 0.5s;
transition-timing-function: ease-in-out;
}
<div class="wrap">
<div class="box2"></div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box1"></div>
<div class="box2"></div>
<div class="box1"></div>
</div>
<button id="btn">submit</button>

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

A guide on extracting/filtering information from JSON files using JavaScript

Is it possible to extract specific data from a JSON file using JavaScript? I have imported a JSON file into my local JavaScript and I am having difficulty in retrieving and displaying certain information. Could someone offer assistance with this? The JS ...

Angular error: Trying to assign a value of type ArrayBuffer to a string type

Is there a way to display a preview of a selected image before uploading it to the server? Here is an example in HTML: <div id="drop_zone" (drop)="dropHandler($event)" (dragover)="onDragover($event)"> <p>drag one or more files to ...

Manipulating Objects with CSS Transform in Global/Local Coordinates

If we take a closer look at our setup: <div id="outside"> <div id="inside">Foo</div> </div> and apply a rotation to the outer element - let's say turning it 45 degrees clockwise: <div id="outside" style="transform: ro ...

Utilizing a JSON object passed from one JavaScript function to another: A comprehensive guide

After creating a function that returns JSON format through an ajax call, I received the following JSON data: { "communication": [{ "communication_name": "None", "communication_id": "1" }], "hardware": [{ "hardware_name ...

Error encountered when running NPM start - file path unable to locate JSON package file

Hello everyone, I'm new here and appreciate any help in advance! I'm currently working on my first project and encountering some challenges. The biggest one is that whenever I try to run npm start, I keep getting an error message: I've att ...

What is the significance of using a double arrow function in Javascript?

Can someone explain the double arrow notation used in the code snippet below? How does the second arrow function get executed if the first one's response is true? And in what scenarios is this notation typically used? async check({ commit }) { ...

Error message: "Unable to POST image with Node/Express (React frontend) while attempting to upload

I am a beginner in Node.JS and currently working on developing a MERN movie ticket booking system. The front-end code snippet provided below showcases the function responsible for uploading an image for a specific movie: export const uploadMovieImage = ( ...

Javascript background image rotation causes a sudden jump to the top of the webpage

I am struggling with a JavaScript issue that I can't seem to figure out. I'm very new to this so any help would be greatly appreciated. I found some code that loads random images into a div element and made some modifications to add a bit of rand ...

"Implementing jQuery toggle and addClass functions in your

How do I modify the class within the same action as a toggle effect, which works independently very well? (I have multiple blocks with the same classes) $(".w_content").hide(); $(".w_target").click(function() { $(this).parent().next('.w_content&apos ...

Refreshing a model using angular.js

I am attempting to reset values in the following way: $scope.initial = [ { data1: 10, data2: 20 } ]; $scope.datas= $scope.initial; $scope.reset = function(){ $scope.datas = $scope.initial; } However, this code ...

Leveraging @font-face for various styles and designs

Google web fonts presents the Droid Serif font in these styles: DroidSerif.ttf DroidSerif-Bold.ttf DroidSerif-BoldItalic.ttf DroidSerif-Italic.ttf I am interested in using the @font-face CSS rule to import all of these variations with the "Droid Serif" f ...

Unforeseen Firefox Problem Arises with display: table CSS Property

The ultimate visual aim is to create a horizontal menu with links that can span multiple lines but are all vertically centered. In modern browsers, this effect can be achieved using CSS with the display: table property. Here is an example of how it can be ...

Looking to dynamically add content to a webpage without needing to refresh the page? Utilizing AJAX can help achieve that

On my website, users have the ability to create posts which are then saved in a database. I would like these posts to be retrieved with a query and displayed on the webpage without having to refresh the page. I understand that I need to implement Ajax for ...

Is there a way to refresh autocomplete/autofill after form submission with a custom JavaScript function?

I've developed a Vue application that includes a form. Once the user clicks on submit, an Ajax request is made using Axios through a JavaScript function. The data being sent is a custom JSON object that I have constructed by combining the information ...

Why does the appearance of my PHP spreadsheet change when I attempt to print it?

After using a CSS stylesheet to position my textboxes correctly, I noticed that in Chrome everything appeared fine. However, when attempting to print the site (Ctrl+P), each sentence and textbox shifted. How can I ensure they remain in place? <!-- #cap ...

Using AJAX to submit a form to a CodeIgniter 3 controller

I am working on adding a notification feature and need to run an ajax query through the controller when a button is clicked. Here's the script I'm using: $('#noti_Button').click(function (e) { e.preventDefault(); ...

How can I make a POST request from one Express.js server to another Express.js server?

I am encountering an issue while trying to send a POST request from an ExpressJS server running on port 3000 to another server running on port 4000. Here is the code snippet I used: var post_options = { url: "http://172.28.49.9:4000/quizResponse", ti ...

Having trouble uploading several files with Multer functionality?

I've encountered an issue with Multer in Node.js where I can't seem to select and upload multiple files. In a previous exercise, I had no trouble uploading a single file, but now I'm struggling with enabling multiple uploads. What am I mis ...

Flask Server produces a response with a considerable delay when accessed through AJAX

I am currently running 2 servers on localhost, each with different ports. One of them is a basic flask server in Python and its code is provided below: from flask import Flask,jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.rout ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...