Iterating through two classes in a Javascript loop

Hello, I'm facing a small obstacle that I'm hoping to overcome using JavaScript/jquery. Essentially, I have multiple div classes and I want to create a loop that adds a class to specific divs without manually assigning an id to each one. The goal is to dynamically add an id or class using JavaScript code.

Here's an example of what I'm trying to achieve:

<div></div><div></div>    
<div></div><div></div>
<div></div><div></div>    
<div></div><div></div>

Currently, I have a structure where two divs form a row. I want to dynamically add a class in a specific pattern to achieve the following layout:

<div class="green"></div>           <div></div>    
<div></div>                         <div class="green"></div>
<div class="green"></div>           <div></div>    
<div></div>                         <div class="green"></div>

It seems like I will need to implement a loop that targets every two divs and repeats the process in reverse.

Answer №1

using jquery

Implement this code snippet in order to apply a class to every second div element.

Check out the DEMO here

 $('div').each(function(i){
   if((i%3) === 0){
    $(this).addClass('green')
   }
 });

Utilizing the :odd and :even selectors

View the DEMO here

 $( "div:odd" ).addClass( "green" );

For the even div elements

 $( "div:even" ).addClass( "green" );

Answer №2

Essentially, what you're looking for is the Zig-Zag pattern.

No need for loops here. You can achieve this using the :nth-child selector like so:

$('div:nth-child(4n+1)').addClass('green'); // Selects 1, 5, 9, 13, ...
$('div:nth-child(4n)').addClass('green'); // Selects 4, 8, 12, 16, ...

See Demo

Check out the pure CSS demonstration below.

body {
  width: 120px;
}
div {
  height: 50px;
  width: 50px;
  background: red;
  margin: 5px;
  float: left;
}
div:nth-child(4n+1) {
  background: green;
}
div:nth-child(4n) {
  background: green;
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

Answer №3

HTML:

<div class="container">
    <div class="box">A</div>
    <div class="box">B</div>
    <div class="box">C</div>
    <div class="box">D</div>
    <div class="box">E</div>
    <div class="box">F</div>
</div>

Vanilla Javascript:

var containers = document.getElementsByClassName("container");

for (var x = 0, xx = containers.length; x < xx; x++) {
    var container = containers[x],
        boxes = container.children;

    for (var y = 0, yy = boxes.length; y < yy; y++) {
        var item = boxes[y];
        if (y % 2 === 0) {
            item.classList.add("highlight");
        }
    }
}

Demo

OR

Using jQuery:

$(".box:even").addClass("highlight");

Demo

Answer №4

To add a decorative touch with alternating backgrounds, you can utilize the CSS pseudo-classes nth-child(even) or nth-child(odd) as demonstrated in the example below:

tr:nth-child(even) {background: #CCC} 
tr:nth-child(odd) {background: #FFF}

Answer №5

One way to access your div elements is by using a for loop along with the childNodes() method in JavaScript. If the element's index is an odd number, you can manually add your desired class to it.

Here is an example:

var elements = parentElement.childNodes();

for (var j = 0; j < elements.length; j++) {
    if (j % 2 === 0) continue;

    elements[j].className = "highlight";
}

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

Is it possible to modify the spacing of menu items in the React Material-ui Drawer component?

Recently, I decided to incorporate Material-UI into a React project for the first time. The AppBar was set up to trigger Drawer, which displayed a list of menu items in the sidebar. However, an issue arose with excessive margin-top spacing. Here is an ill ...

Enhanced efficiency in the interaction between front-end JavaScript and back-end JavaScript

As a frontend developer, I find myself in the unique position of working on a project that involves processing a large amount of data in my nodeJS backend (while using reactJS for the front end). After the necessary data processing is completed in the bac ...

No response observed upon clicking on the li element within the personalized context menu

I created a custom context menu that pops up when you click on an li element within an unordered list. I'm trying to trigger an alert when clicking on an li item inside the context menu, but it's not working as expected. To handle this dynamic c ...

Creating a user-friendly navigation menu: A step-by-step guide

I need help creating a navigation menu for my website that isn't functioning properly. Here is the code I am currently using: body{ margin: 0px; padding: 0px; } nav > ul{ margin: 0px; padding: 0px; } nav > ul > li{ fl ...

Is it possible for me to transform this code into a useful helper function?

I am looking to optimize this conditional code by converting it into a helper function using a switch statement instead of multiple if statements. How can I achieve this in a separate file and then import it back into my component seamlessly? import { ...

Tallying discarded objects post removal from drop zone

Is there a way to accurately count dropped items within a dropped area? I have created an example that seems to be working fine but with one minor issue. When I begin removing items, the count does not include the first item and only starts decreasing afte ...

"Looking to disable the browser shortcut for ctrl-N and instead trigger a function when this key combination is pressed? Check out the JS Fiddle example provided below

I recently incorporated the library shortcut.js from In my project, I attempted to execute a function when CTRL + N is pressed. The function executed as expected; however, since CTRL + N is a browser shortcut for opening a new window in Mozilla 8, it also ...

Encountering an "Error: Invalid string length" while attempting to iterate over the JavaScript object

I am brand new to the world of programming and currently working on developing my very first app. It's a daily expenses tracker that I have been struggling with. The issue I am facing is when a user adds a new item (such as coffee) and an amount, a ne ...

What is causing the auto-fill property in CSS Grid to malfunction when used in a vertical column direction?

I've been experimenting with the auto-fill property in grid rows, but it's not quite working as I intended. My goal is to create rows with a height of minmax(140px, 200px), however, what I'm actually getting is one row at 200px height and th ...

Updating the variables of HTML components using JavaScript after making an AJAX request

I am using ajax to fetch a list of user data. But after this ajax call, I need to display the data in an HTML structure like a datasheet for each user. My question is how can I store the HTML code in a functional and elegant way to maintain readability and ...

Is it advisable to prevent Set and Map from having unspecified generics in TypeScript?

Upon reviewing some old code that I wrote, I realized that I had neglected to specify a generic type for a Set. The type was set as Set<unknown>. Strangely, despite this, I found that I could still utilize all the methods of the Set without encounter ...

Excessive CPU/GPU usage caused by CSS transition animations

I am currently working on a small element on my website that involves a random size change in one of the DOM elements. const theDiv = document.getElementById("the-div"); function animate(){ const value = Math.floor(Math.random() * 200); theDiv.sty ...

The hover effect for a :before class is not functioning as intended

I have created a dropdown menu with a triangle at the top in this style: When the cursor hovers over only the triangle, it appears like this: However, when the cursor is over the div, the hover effect for both elements is activated as shown here: I am t ...

The Next.js component only appears after a page reload

Essentially, I have a nested component that is supposed to render with the parent component and it works fine when the server initially starts. However, the issue arises when switching back from another page – some of the nested components disappear. A ...

Challenges encountered with pagination functionality within Datatables integration

I'm encountering a small problem with pagination. When using the "four_button" type, the table appears correctly (with accurate pagination buttons), but clicking on any of the pagination buttons (Next, Previous, etc...) results in an error saying "fnC ...

Looking to transmit data to your HTML page and incorporate AJAX for your Single Page Application on a NodeJS server with express.js framework?

Is there a way to display the form submitted data on a different HTML page? I am collecting user data on the 1st page (page1.html) and after storing this data in the database, I want to showcase the submitted values on another page, specifically (page4.ht ...

Do not apply hover effect to a particular child div when the hover effect is already applied to the parent

I am encountering a problem with the hover effect. I have 3 child div's structured as follows: <div class="parent"> <div class="child1">A</div> <div class="child2">B</div> <div class="child3">C</div ...

What is the process of adding a unique model to three.js?

Despite trying numerous solutions to a common problem, I am still unable to import my 3D model in Three.js using the following code: <script src="https://threejs.org/build/three.min.js"></script> <script src="https://cdn.rawgi ...

What strategies can I implement to ensure my modal dialog box remains responsive? Adjusting the window size causes the modal box to malfunction and lose its structure

Whenever I adjust the size of the browser window, the elements inside the modal box become misaligned. HTML <div class='modal'> <div class='modal-content'> </div> </div> Below is the CSS for the modal ...

populating a HTML image tag 'src' attribute with data extracted from API javascript code

Hey there! I'm currently working on integrating an image element from the openweatherAPI that corresponds to the weather icon retrieved from the JSON data when a user inputs a city. This means displaying images like scattered clouds or clear skies bas ...