Is there a way to assign classes to elements within a sequence based on their index positions?

My goal is to create a list with alternating classes that have a start and end class for each set of items. For example, I currently have the following code:

<div class="wrap">
  <div class="item-a"></div>
  <div class="item-a"></div>
  <div class="item-a"></div>
  <div class="item-a"></div>
  <div class="item-b"></div>
  <div class="item-b"></div>
  <div class="item-b"></div>
  <div class="item-a"></div>
  <div class="item-a"></div>
  <div class="item-a"></div>
  <div class="item-b"></div>
  <div class="item-b"></div>
</div>

I want to achieve the following structure:

<div class="wrap">
  <div class="item-a start"></div>
  <div class="item-a"></div>
  <div class="item-a"></div>
  <div class="item-a end"></div>
  <div class="item-b start"></div>
  <div class="item-b"></div>
  <div class="item-b end"></div>
  <div class="item-a start"></div>
  <div class="item-a"></div>
  <div class="item-a end"></div>
  <div class="item-b start"></div>
  <div class="item-b end"></div>
</div>

I found a solution involving jQuery, but I need to accomplish this using plain JavaScript as I do not have jQuery in my environment.

In my React project, I am working with an array of objects retrieved from an API like this:

arr = [
  {class:"left", id:"0", direction:0 },
  {class:"right", id:"1", direction:1 },
  {class:"right", id:"2", direction:1 },
  {class:"left", id:"3", direction:0 },
  {class:"left", id:"4", direction:0 },
  {class:"left", id:"5", direction:0 },
  {class:"right", id:"6", direction:1 },
  {class:"right", id:"7", direction:1 },
]

I have attempted to use a for loop to achieve this, but so far have been unsuccessful.

Answer №1

Alright, let's address this issue first. The error lies in the array of objects where you have:

id='0',

instead of:

id:'0'.

To assign each element its corresponding class in the array, here's what you can do:

var arr = [
    {class:"left", id:"0" },
    {class:"right", id:"1" },
    {class:"right", id:"2" },
    {class:"left", id:"3" },
    {class:"left", id:"4" },
    {class:"left", id:"5" },
    {class:"right", id:"6" },
    {class:"right", id:"7" },
  ]
  var cArr = Array.from(document.querySelector(".wrap").children);
  // Convert NodeList into an Array for compatibility
  for(var i in cArr) {
    // Loop through elements
    if(arr[i] === undefined || arr[i].class === undefined) continue;
    // Ensure that object in arr is defined
    cArr[i].classList.add(arr[i].class);
    // Assign the specified class from arr to the element
    console.log(cArr[i]);
    // Verify that the class was successfully added
  }
<!DOCTYPE html>
<html>
<head>
<title>classes</title>
<style>
</style>
</head>
<body>

    <div class="wrap">
        <div class="item-a 1">1</div>
        <div class="item-a 2">2</div>
        <div class="item-a 3">3</div>
        <div class="item-a 4">4</div>
        <div class="item-b 5">5</div>
        <div class="item-b 6">6</div>
        <div class="item-b 7">7</div>
        <div class="item-a 8">8</div>
        <div class="item-a 9">9</div>
        <div class="item-a 10">10</div>
        <div class="item-b 11">11</div>
        <div class="item-b 12">12</div>
    </div>
    
    <script>

    </script>

</body>
</html>

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

Having difficulty interpreting the date

Currently, I am attempting to extract the date from the given format: dateFormat: "d-M-y" // results in 10-Oct-13 To format the date, I am utilizing jQuery UI. Here is the code snippet I am using: var d1 = new Date("10-Oct-13"); alert(d1); //Works cor ...

Creating a Distinctive HTML Structure with Div Percentage (HTML 4)

I am new to web design and have a unique approach; I believe in the importance of flexibility. It puzzles me why pixels (px) are commonly used instead of percentages, maybe my perspective is misunderstood. I've been on the hunt for a basic HTML layo ...

Transform a nested JSON array into a JavaScript array

I have a JSON array that looks like this (shortened for simplicity): [ { "name": null, "code": null, "results": [ { "date": "2012-04-28T06:00:00.000Z", "name": null, "value": 135, "unit": "MG/DL", ...

What methods are available for debugging JavaScript in a embedded browser within Windows?

I am currently facing an issue where I need to debug Javascript (Jquery) sources in an embedded browser on Windows 7 and XP while using Sketchup. I attempted using console.log, however it affected the layout of the app. Does anyone have a solution for th ...

Arranging mat-checkboxes in a vertical stack inside a mat-grid-tile component of a mat-grid-list

I'm looking to create a grid list with 2 columns, each containing 2 checkboxes stacked vertically. While I found this helpful question, it still involves a lot of nested divs. Is there a cleaner way to achieve this layout? Here's how I currentl ...

Controlling the behavior of React components in response to updates

I'm currently learning ReactJs and utilizing the ExtReact framework for my project. I have successfully implemented a grid with pagination, which is functioning well. I customized the spinner that appears during data loading and it works as expected ...

retrieve the height value of a div element using AngularJS

I'm having trouble retrieving the updated height of a div using AngularJS. It seems to only provide the initial value and does not update as expected: vm.summaryHeight = $(".history-log-container").height(); console.log(vm.summaryHeight);//always dis ...

Troubleshooting the "@material-ui/core" issue in React: Step-by-step guide

Issue with React: Unable to locate the '@material-ui/core' module in 'C:\Users\user\Downloads\inTech'22-Web Development (EDUGEN)\edu-gen\src\components' Resolution Command: To resolve, run npm in ...

What is the best way to have my items fill the entire column space using flexbox?

Having 2 containers and wanting them to have the same height has been a challenge. I've been experimenting with flexbox and the flex-direction: column (flex-column) property, but I can't seem to get each element to divide the available container ...

Avoiding the use of angle brackets in XSLT语

Looking to replace a sequence containing '.\s+\w+' with a line break This is what I currently have: <xsl:value-of select="replace($fdesc,'[.][ ]+\w+','<br/>')" /> However, I am encountering an er ...

Issues with Grunt functionality after installation on Ubuntu

I successfully installed Grunt by running the following commands in the terminal: sudo apt-get install nodejs sudo apt-get install npm npm install -g grunt-cli After executing npm install -g grunt-cli, here is the output from the terminal: (output he ...

The applet failed to load on the HTML webpage

I'm having trouble getting this applet to load on an HTML page. I've already added full permissions in the java.policy file and I'm using the default HTML file from NetBeans Applet's output. /* Hearts Cards Game with AI*/ import java.a ...

Creating a tournament bracket in HTML using a table structure

For the past 3 weeks, I've been grappling with a problem that has me stumped. I just can't seem to figure it out for the life of me. What I'm attempting to achieve is a specific output or presentation using tables. Here's an example of ...

Observes the behavior of a React component with the context.router property being undefined

Currently, I am conducting a test on a react component using chai, karma, and enzyme. mount( <Provider store={configureStore(mockContext, null)}> <Component {...props} /> </Provider> ) In the component, I am utilizing context.router.l ...

What is the most effective way to append a new key-value pair to the end of an OrderedMap?

Possible duplicate: Adding Items in OrderedMap using Immutable.js Utilizing redux store and Immutable js with OrderedMap. Structure of Redux store: { "app": { "name": "Test app", "dataPack":{ "chemID": "aaaa", ...

Using Spring Boot RestController to Serve HTML Pages

I'm having trouble accessing the HTML page I created. Here is an overview of my project: https://i.sstatic.net/Wvmus.png This is the "IndexController" class: @RestController @AllArgsConstructor @RequestMapping(path = "/webpage") public class IndexCo ...

Utilizing Nested Masterpages in conjunction with CSS files

I am faced with a situation where I have two masterpages - one named main.Master and the other search.Master. The search.Master is actually a nested masterpage, residing within the main.Master. In order to ensure that my CSS files function properly with t ...

Create a unique Bootstrap 5 carousel featuring a single progress bar

Hey guys, I'm having some trouble with my Bootstrap 5 carousel. I want to add a progress bar with left and right arrows, and also the number of slides displayed, just like in this image: https://i.sstatic.net/pqOMy.jpg I did some research and found ...

Add data to the beginning of a textarea

This JQuery code has been created to prepend input from a textarea $(document).ready(function() { var data = <?php echo $data; ?>; $('#standard_response').on('change', function() { var sequence = $(this).val(); ...

Change the text field's border color if the field is not empty

On my website, there is a TextField where users can enter values to perform a site search. My question pertains to the border color of this field. Normally, the border color is black when the field is not in use. However, when a user clicks on the field an ...