Using jQuery to alter the class of div elements in a specific sequence

Currently, I am working on a blog layout using Bootstrap and have encountered an issue.

The specific layout requirement is to have the first two divs as col-md-3 (NORMAL), followed by the next 2 divs as col-md-6 (WIDE), then repeating this pattern for the next 4 divs as col-md-3 (NORMAL), the next 2 divs as col-md-6(WIDE), and so on.

I have attempted a method in CodePen (code below) which achieves the desired layout. However, due to my limited experience with jQuery, I believe there might be a more efficient way to accomplish this. Any guidance or assistance you can provide would be greatly appreciated!

HTML:

  <div class="container">
  <div class="row" id="blog">
    <div>Normal</div>
    <div class="">Normal</div>
    <div class="">Wide</div>
    ... (more HTML code)
    <div class="">Normal</div>
  </div>
</div>

jQuery used:

$("#blog div").each(function(i) {
var newClass = 'col-md-3 red';
if (i == 2 || i == 3 || i == 8 || i == 9 || i == 14 || i == 15 || i == 20 || i == 21 || i == 26 || i == 27 || i == 32 || i == 33) {
newClass = 'col-md-6 blue';
}
$(this).addClass(newClass);
});

Answer №1

To achieve this, you can utilize both the .not() and .filter() methods.

$('#blog div').addClass('col-md-3 red')         // applying red class to all div elements
  .not(':lt(2)')                                // excluding the first two Normal elements
  .filter(function(i){                          // filtering for Wide elements
    return (i % 6 == 0) || ( (i % 6) - 1 == 0)  // selecting every 6th element and its next neighbor
  }).addClass('col-md-6 blue');                 // adding 'blue' class to the Wide elements
.red{
  background : red;
}
.blue{
  background : blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row" id="blog">
    <div>Normal</div>
    <div class="">Normal</div>
    <div class="">Wide</div>
    <div class="">Wide</div>
    // more div elements...
  </div>
</div>

Answer №2

This solution loops through each individual div element and assigns the corresponding class based on a predefined order stored in a pattern array. While it may not be significantly more concise than your current implementation, it offers a key advantage - flexibility. If you decide to adjust the number of div elements or modify the pattern itself, simply updating the items in the pattern array will yield an immediate change in output.

elements = $("#blog").children();
pattern = ['col-md-3','col-md-3',
          'col-md-6','col-md-6',
          'col-md-3', 'col-md-3'];
  pattern_val = 0;
  for (var i=0;i<elements.length;i++) {
    if (pattern_val < 6) {
      $(elements[i]).addClass(pattern[pattern_val]);
      pattern_val += 1;
    }
    else {
      pattern_val = 0;
      $(elements[i]).addClass(pattern[pattern_val]);
      pattern_val += 1;
    }
};

For a live demonstration, check out this CodePen example.

Answer №3

retrieve the current element's content using the text method.

$("#blog div").each(function(i) {
    var newClass = 'col-md-3 red';
    var text = $(this).text();
    if (text == "Wide") {
        newClass = 'col-md-6 blue';
    }
    $(this).addClass(newClass);
}

Answer №4

This choice is mine to make. It involves objects and their respective keys. Each object (class) is linked to specific keys (index).

let obj = {
  "col-md-3": [1, 2, 5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20, 23, 24, 25, 26, 29, 30, 31, 32, 35, 36],
  "col-md-6": [3, 4, 9, 10, 15, 16, 21, 22, 27, 28, 33, 34]
}

let objKeys = Object.keys(obj),
    objValues = Object.values(obj);

let nodes = document.querySelectorAll("#blog div");

for (var i = 0; i < nodes.length; i++) {            
    let index = objValues.findIndex(id => id.indexOf(i + 1) > -1)
    
    if (index > -1) {
        nodes[i].classList.add(objKeys[index]);
    }
}

$(nodes).each(function(i) {
  $(this).addClass(obj[i]);
});
.col-md-3, 
.col-md-6 {
  border: 1px solid green;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="row" id="blog">
    <div class="">Normal</div>

	<!-- Additional code trimmed for brevity -->

    <div class="">Wide</div>
    <div class="">Normal</div>
  </div>
</div>

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

Capture selected items from checkboxes and incorporate them into the CSS styling

I would like to give users the ability to choose from a series of checkboxes with additional options to add to their CSS. Using JavaScript, I am searching for checked boxes, extracting their names, adding them to a list, and then inserting that list into ...

Utilize or Bring in an external JavaScript file within Ionic 2

Currently working with Ionic 2 and Typescript Angular 2 and facing an issue. I need to utilize an external JavaScript file located at . How can I import or include this in my project? ...

Display the result from an Ajax call

public ArrayList getConsignmentsID(final DB database, String searchValue) { System.out.println("inside getConsignmentsID function"); Consignment consignment = new Consignment(); DBConnection dbConnection = new DBConnection("mongodb://localhost" ...

Arrange an item independently of surrounding elements

Is it possible to position an element across two columns, starting in the middle of the second column? The columns are defined by divs. Could this be achieved through z-index positioning? ...

Obtain a transformed mesh that has been displaced using a displacementMap within three.js

Seeking to extract and export the mesh affected by a displacementMap. The displacement of vertexes is determined by this line in the shader (taken from three.js/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl): transformed += normalize(obje ...

Customizing Vue: Implementing an automatic addition of attributes to elements when using v-on:click directive

We are currently working with single file Vue components and we're facing a challenge in our mousemove event handler. We want to be able to determine if the target element is clickable. Within our Vue templates, we utilize v-on directives such as: v- ...

Creating a horizontal HTML table to display the output of a foreach loop

I am a new member who has been searching for a solution on how to display the output of a PHP foreach loop in a horizontal HTML table. Inside the Data Set file, which is in .xml format, there are multiple Series with 24 x TIME_PERIOD's and 24 x OBS_VA ...

Retrieving the scrollTop() property of a specific element within an Iframe

Can you retrieve the scrollTop or offset value of an element within an iFrame? For example: $("iframe").contents(".controlPanel").scrollTop(); Is there another method to achieve this? When I attempt this, I receive a null return value. ...

Tips for implementing JavaScript or jQuery to enable page transitions in a single-page website

Currently, I am in the process of developing a website that encompasses both front-end and back-end elements. One challenge I am facing involves figuring out how to utilize JavaScript/jQuery to transition between pages within a single-page website. The ta ...

How can you refresh the source element?

Is there a way to make the browser reload a single element on the page (such as 'src' or 'div')? I have tried using this code: $("div#imgAppendHere").html("<img id=\"img\" src=\"/photos/" + recipe.id + ".png\" he ...

Utilizing Angular's web architecture involves nesting components and concealing them with the ng-hide directive

I'm currently working on an Angular 1.X application and have encountered a scenario where a component is shared across three different pages. Within the main component, there are several nested components but only two of them should be displayed on a ...

Adjusting the background color of the list item

I'm looking for a way to change the background color of the li tag when the user focuses on the input, similar to what can be seen at the bottom of this page here. After researching similar questions, it appears that achieving this effect in pure CSS ...

Adding style tags dynamically to a component and then encapsulating the styles again (using Angular)

Currently, I am in the process of upgrading from AngularJS to Angular. Our app is currently a hybrid one being bundled up with webpack instead of just angular cli. Due to this setup, we have encountered issues where our css or scss files are not correctly ...

Having Trouble with Centering in Bootstrap 4

I'm a bit puzzled about how to center the h2 element. This is my first time using Bootstrap 4, transitioning from Bootstrap 3, so maybe there's a difference that I'm not aware of? Any guidance on this matter would be greatly appreciated. Tha ...

Tips for enhancing the speed of drawing circles in mouse movement using JS and CANVAS

My current script allows me to draw a circle during mousemove, but it's not as fast as I'd like. Before drawing the circle, I gather the color pixel during mousemove in order to draw a circle on the canvas with the picked color. I came across ...

Executing a fundamental three.js program

After downloading three.js from the official site, I encountered a strange error while trying to run a basic file. However, when I replaced the local import of the three.js file with a CDN, it started working properly. Can someone assist me in getting the ...

What is the best way to retrieve data from only the first few XML entries using AJAX?

As someone who is fairly new to jquery and ajax, I have created an XML file for dynamically generating a news page. The other pages on my site include a news bar that pulls updates from the same file. Currently, the news bar displays every single news it ...

Attempting to apply a class to selected elements, however, the conditional statement is not functioning as intended

<div> <div class=category> Special Occasions </div> <div class=category> Holidays </div> <div class=category> Graduations </div> <div class=category> Retirements </div> </div> <ul> <li c ...

progressing both forward and backward through every month

I am currently working on a project that involves creating a calendar using JavaScript. I have implemented functionalities where I can navigate back and forth through months, fetching the days within each month. However, I am facing an issue where if I go ...

Having trouble populating the dropdown menu with data retrieved from the database

I'm having an issue fetching values from the database to populate a drop-down list using jQuery. Unfortunately, nothing is displaying in the dropdown list. Below is the code snippet: getlist.php <?php $conn =mysqli_connect("localhost&q ...