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

Steps to convert a phone number into JSON format

The primary focus Upon receiving an MQTT packet, it is displayed as an ASCII array in the buffer after being printed using stringify: packet = { "cmd": "publish", "retain": true, "qos": 1, "dup& ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

What's the best way to handle the output of an HTTP request in my specific situation?

Struggling to pass http request results from parent controller to child controller... This is what I have: <div ng-controller = "parentCtrl"> <button ng-click="callApi()">click me</button> <div ng-controller = "childCtrl"& ...

Identifying activity on a handheld device

I am currently working on a website and I have noticed that it doesn't work as well on mobile devices as it does on desktop. There are performance issues that need to be addressed. I've seen other websites redirecting users to a different page wh ...

Manipulate SVG elements by dragging them along the boundary of the path

Looking to achieve a specific functionality where I can drag and drop an element along the edges of a drawn path, rather than inside the path itself. To clarify, the goal is to move the red marked element on the black line bordering the path, allowing move ...

Actions cannot be performed on elements generated by ng-repeat

I am facing a challenge where I need to display a list of languages on a page, allowing users to change their selections based on previous choices. To achieve this functionality, I have written the following code snippet: ... <tbody> & ...

Transforming table headers in Rmarkdown ioslides

I am experimenting with creating a custom table format for tables generated using the ioslides_presentation output type in Rmarkdown with Rstudio Version 0.98.1028. However, I'm facing difficulty in modifying the styling of the table headers. Below i ...

Basic application - angular has not been declared

I'm currently diving into the realm of javascript and angularjs, following along with the tutorials on . After setting up a basic IntelliJ javascript project, I created two essential files: index.html <!DOCTYPE html> <html lang="en"> ...

The FAB button animation is causing delays in the transition process and is not functioning as originally anticipated

I am facing an issue with the FAB button and 3 Icons. The functionality is working fine on click for both show and hide actions, but the transition is too delayed. I want the icons to appear step by step, even though I have adjusted the transition delay se ...

Updating image URL for grouped objects with Fabric JS

Check out this link :http://jsfiddle.net/mishragaurav31/ang58fcL/#base I created two groups of objects; one consisting of a circle and text, and the other with two images. When I try to change attributes for group 1, it works fine. However, when attempt ...

Combining the jquery-UI slider functionality with the canvas rotate() method

Is there a way to rotate an image using html2canvas plugin and jQuery UI slider? I am new to programming and need some guidance on how to achieve this feature. Here is my current progress: http://jsfiddle.net/davadi/3d3wbpt7/3/ ` $("#slider").slider({ ...

Anticipating the execution of pool.query within a callback function in the Express framework

Within an Express post endpoint, I am utilizing crypto.generateKeyPair. After generating the key pair, I wish to store it in my database and then return the ID of the inserted row within the same endpoint. Here is the code snippet for the endpoint: app.p ...

Is there a way to have dynamic content from angularJS show up in an iframe?

When working with tabular content generated using ng-repeat in AngularJS, it is important to find a way to display this content within an iframe. The goal is to allow users to drag and resize the content as needed. However, using the iframe src attribute ...

An issue with Axios request in a cordova app using a signed version

Currently, I am in the process of developing a Cordova application utilizing Axios and React. The interesting part is that everything runs smoothly when I build the app with Cordova and test it on my phone using the APK. However, once I sign, zipalign it, ...

Switching classes in real time with JavaScript

I'm struggling to understand how to toggle a class based on the anchor text that is clicked. <div> <a id="Menu1" href="#">Menu</a> <div id="subMenu1" class="subLevel"> <p>stuff</p> </div> <div> <a i ...

Leveraging webpack2 for code splitting with the CommonsChunkPlugin

I encountered an issue while using code splitting and the CommonsChunkPlugin. My previous experience with require.js involved files being automatically cached. Additionally, I have configured my webpack with libraryTarget: 'amd'. When looking at ...

Tips for passing input fields from a React Function component to a function

How can I retrieve the values from 4 input fields in my react functional component using a function called contactMeButtonPressed? The inputs include name, email, company name, and message when the contact me button is clicked. Do I need to implement stat ...

What are some ways to eliminate the excess white space beneath the footer in HTML?

After creating a responsive webpage that works flawlessly on mobile devices and tablets, I noticed a problem with the footer when viewed on desktop. There is an empty white space at the end of the webpage, and upon inspecting the browser, it focuses on the ...

Tips for retrieving return values from an ajax form submission

When using ajax to submit a form, I encountered an issue where the process would halt at api.php and not return to the ajax success. Below is the code snippet: <form method="POST" id="form_1" action="../api.php" enctype="multipart/form-data" novalidate ...

Leveraging AngularJS to send a post request to the server through the $http

Can't seem to find a solution to my Angular issue, despite searching for it extensively? After starting to learn Angular recently, I've put together the following code based on various online resources. Here's the HTML: <div data-ng-ap ...