Several DIVs with the same class can have varying CSS values

I am looking to modify the left-margin value of various separate DIVs using JavaScript. The challenge is:

  1. I only want to use a single className, and
  2. I want the margin to increase by 100px for each instance of the class. This way, instead of all the DIVs overlapping, they will be evenly spaced out: the first at margin-left:0px, the second at margin-left:100px, the third at margin-left:200px, and so on.

Currently, I have code that applies the same margin-left to all DIVs.

<script>
    b = document.getElementsByClassName('spacing');
    for (i = 0; i < b.length; i++) {
    b[i].style.marginLeft = "100px";
    }
</script>

I am wondering if there is a way to have the JavaScript dynamically find each instance of the class sequentially and instead of just setting margin-left: 100px for all, to compute something like (margin applied to last instance of class + X) so that each of the 100 DIVs with the same className will have a unique marginLeft value?

Answer №1

Indeed, there is a solution to this issue. You can simply calculate the margin by multiplying the iteration number like so: i*100+'px' instead of using "100px".

var b = document.getElementsByClassName('spacing');
    for (i = 0; i < b.length; i++) {
      b[i].style.marginLeft = i*5+'px';
    }

Take a look at this functional example

Answer №2

The key is to monitor the increase in margin with each loop iteration:

var elements = document.getElementsByClassName('spacing');
var marginIncrease = 0;
for (j = 0; j < elements.length; j++) {
   marginIncrease += 100;
   elements[j].style.marginLeft = marginIncrease + "px";
}

Give it a try and see if it works for you.

Take a look at a demo here: https://jsfiddle.net/d9y45rag/

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

Merge the content of a single file with the contents of several other files using Gulp

I'm still getting the hang of Gulp, so I hope this question isn't too basic. My project is pretty complex with multiple files, and thanks to Gulp's magic, I can combine, minify, babel, and more. I've been using Grunt for a long time, so ...

Causes of the error message 'TypeError: res.render is not a function'

I have set up an express application with the following code: var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/user'); var request = require(&a ...

Node.js client-sessions malfunction when not utilized as a primary callback

When utilizing express.Router, I'm attempting to create a middleware for a particular router in my application that will establish and handle a session. However, this approach fails if the client-sessions session is not invoked directly by Router().us ...

What is the reason behind the necessity of using setTimeout with a delay of at least 50ms for JS .focus()

Problem While creating a page for a client at work, I encountered an issue with a slide-out search bar. When clicking the button to open the search input field (which starts off hidden), I want the focus to shift to that input field. Oddly, I found that ...

Issue occurred: The error "Undefined offset 1" was encountered while trying to upload a file via

Every time I try to pass data into my file upload controller, I keep encountering an error message that says undefined offset: 1. function TestFileUpload() { $i=0; if(!isset($_FILES[$i]) ) { echo "No file is being uploaded"; } el ...

How can I slow down the response time in Express Node?

I have set up a route that triggers an asynchronous function when the URL is accessed. This function will eventually return a value, which I want to use as the response for the get request. However, I am facing an issue with delaying the response until the ...

An easy way to adjust the date format when linking a date in ng-model with md-datepicker

<md-input-container> <label>Scheduled Date</label> <md-datepicker ng-model="editVersionCtrl.selectedPlannedDate" ng-change="editVersionCtrl.checkPlannedDate()"> </md-datepicker> </md-input-container> ...

tag directive not functioning properly

I have encountered an issue while trying to create a simple custom directive. When I specify the directive as <div my-info></div> in my HTML file, it works fine. However, when I specify it as <my-info></my-info>, it does not work. ...

innerhtml does not display the entire array contents

I'm facing an issue with my innerHTML output where it seems to be displaying one less value than expected from the array. I've been unable to pinpoint the exact problem. await fetch(urlbody, bodyrequestOptions) .then((response) => response ...

Display updated text on hover over button panel

Is it possible to achieve the following using only CSS without any JavaScript? The desired outcome is a div containing two font awesome icons aligned to the right side. Specifically, I am looking for: - Icon of a pen that reacts on mouse hover - Icon o ...

Export nested objects from an AngularJS JSON array to a CSV file

When I download my data into a CSV file, the display setting is showing as "[object Object]". This is not the desired outcome. https://i.stack.imgur.com/ej2UO.png The expected display should look like this: https://i.stack.imgur.com/8JJ88.png This is p ...

Perform the action when the button is clicked

I'm struggling with finding a solution to this problem. I have an input field and a submit button. My goal is to update the value of a variable to match the value in the input field when the submit button is clicked. Additionally, I need to execute a ...

What could be causing the problem with my CSS background-image being referenced correctly?

Everything seems to be in order: background-image: url(./dir/img.jpg); However, I encounter a 404 error when attempting to reference an image using this approach: index.html <div style="--url: url(./dir/img.jpg);"></div> css backg ...

What is the method for aligning a button label to the left and an icon to the right?

I have a list of items and I want to display label text on the left and a check icon on the right. This works fine when the text is short, but when I added the textOverflow property, the icon gets hidden along with the rest of the text. Here is my list ...

Embedding SVG styling directly into the HTML document

When importing svg images with color into Mapbox Studio, they appear as black and white. The troubleshooting website mentions: If your SVG appears black after adding to Mapbox Studio, it may be due to using style properties in tags instead of inline sty ...

What steps should be taken to resolve the update problem in Sequelize?

Having an issue with the update method in MySQL ORM. User.update({ ResetPasswordToken : resetPasswordToken },{ where: { UserName: 'testuser' } }) Receive this Sequelize Log: Running query: UPDATE Users SET ResetPasswordToken=?,updat ...

The div is lacking in height

I have 3 divs that belong to the stackContainer class: .stackContainer { position: relative; } Within these divs, I want multiple elements stacked on top of each other. To achieve this, I use the following code: .stackItem { position: absolute; ...

Load components dynamically and place them in a flexible position based on the context

UPDATE (After gaining a better understanding of the issue): I'm trying to display a component based on where the user clicks (specifically, which table row). Using ng2-smart-table, I've encountered an issue where there isn't a suitable sele ...

Excess padding in Internet Explorer 7 when a table is nested within a div tag

I have exhausted all potential solutions found on the internet and still cannot seem to solve this issue. Here is an example page that highlights the problem: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/l ...

Changing CSS image properties: A step-by-step guide

I've come across a strange conflict between Twitter Bootstrap (2.2.1) and Ad-Gallery in Internet Explorer. It seems that certain lines in bootstrap.min.css are causing issues, preventing images from displaying: img{max-width:100%;width:auto\9;h ...