A guide on using wrapAll within an each loop in jQuery

I have a series of div elements in my HTML code:

<div class="mainClass class_1"></div>
<div class="mainClass class_1"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_3"></div>
<div class="mainClass class_3"></div>
<div class="mainClass class_3"></div>
<div class="mainClass class_4"></div>
<div class="mainClass class_4"></div>

I am looking to organize them as follows:

<div class="wrapper">
  <div class="mainClass class_1"></div>
  <div class="mainClass class_1"></div
</div>
<div class="wrapper">
   <div class="mainClass class_2"></div>
   <div class="mainClass class_2"></div>
   <div class="mainClass class_2"></div>
   <div class="mainClass class_2"></div>
</div>
<div class="wrapper">
   <div class="mainClass class_3"></div>
   <div class="mainClass class_3"></div>
   <div class="mainClass class_3"></div>
</div>
<div class="wrapper">
   <div class="mainClass class_4"></div>
   <div class="mainClass class_4"></div>
</div>

How can I achieve this layout using an each loop and wrapAll (or any other method) with jQuery? I want to avoid manually adding the wrapper for each class (class_1, class_2, class_3 ... ).

Thank you for your assistance!

Answer №1

When working with multiple classes grouped together, it is important to extract the specific class names like class_1, class_2, and so on. In the each loop function, you can then utilize the .wrapAll() method to wrap them accordingly:

$('.mainClass').each(function(i, div){
   var clazz = this.className.split(/\s/)[1];
   if(!$(this).parent().is('.wrapper')){
      $(`.${clazz}`).wrapAll($('<div/>',{ class: 'wrapper'}))
   }
})
.wrapper{ background:yellow; margin:10px; padding:5px; }
.mainClass{ height: 20px; }
.class_1{ border:solid 1px purple; margin-bottom:10px;}
.class_2{ border:solid 1px orange; margin-bottom:10px;}
.class_3{ border:solid 1px green; margin-bottom:10px;}
.class_4{ border:solid 1px red; margin-bottom:10px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="mainClass class_1"></div>
<div class="mainClass class_1"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_3"></div>
<div class="mainClass class_3"></div>
<div class="mainClass class_3"></div>
<div class="mainClass class_4"></div>
<div class="mainClass class_4"></div>

Answer №2

If you want to wrap each element with the same class using jQuery, you can utilize the wrapAll function as demonstrated in the example below:

$(".content > div").each(function() {
    $(".content > ." + this.className).wrapAll("<div class='wrapper' />");
});
div:not(.content):not(.wrapper){
    height: 10px;
    background: #0fc0fc;
    margin-bottom: 10px;
}

.wrapper {
    border: 1px solid #ff0000;
    margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
<div class="class_1"></div>
<div class="class_1"></div>
<div class="class_2"></div>
<div class="class_2"></div>
<div class="class_2"></div>
<div class="class_2"></div>
<div class="class_3"></div>
<div class="class_3"></div>
<div class="class_3"></div>
<div class="class_4"></div>
<div class="class_4"></div>
</div>

Answer №3

Hey there, have you ever thought about using jQuery to select all the div elements and then looping through them to customize their behavior? For example:

<div class="mainClass class_1"></div>
<div class="mainClass class_1"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_2"></div>
<div class="mainClass class_3"></div>
<div class="mainClass class_3"></div>
<div class="mainClass class_3"></div>
<div class="mainClass class_4"></div>
<div class="mainClass class_4"></div>

Then you can execute some jQuery operations like this:

$cont = $('div');
var content1 = '<div class="wrapper"><div>';
$.each($cont, function(k,v) {
   if($(v).hasClass('class_1')){
        //content for div with class_1
   } else if($(v).hasClass('class_2')) {
       //content for div with class_2
   } else {
       //include rest of the content
   }
});

This is just a basic idea of how you can generate custom formatted content using jQuery. Hope this explanation helps!

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

Capturing mouse clicks in Javascript: a guide to detecting when the mouse moves between mousedown and mouseup events

I have been working on a website that features a scrolling JavaScript timeline, inspired by the code found in this tutorial. You can check out the demo for this tutorial here. One issue I've encountered is when a user attempts to drag the timeline an ...

Utilizing a JSON object passed from one JavaScript function to another: A comprehensive guide

After creating a function that returns JSON format through an ajax call, I received the following JSON data: { "communication": [{ "communication_name": "None", "communication_id": "1" }], "hardware": [{ "hardware_name ...

ng-repeat dysregulating the binding of directive models

<input-directive model="config.shared.product.whatevers[0]"></input-directive> <!-- This code is functioning correctly, however the following does not bind properly --> <td ng-repeat="whatever in config.shared.product.whatevers trac ...

Adjust the Size of Bootstrap 4 Dropdown Caret Icon

Currently, I am using the Bootstrap v4 framework on my HTML page. I am looking to resize or increase the caret size in my dropdown list. Does anyone have any tips on how to accomplish this? https://i.sstatic.net/kCNPK.png Below is the code snippet: < ...

Error message: The function .datepicker('getDate') caused an Uncaught TypeError: Data[option] error

Encountering an issue with the code data[option] is not a function when attempting to utilize .datepicker('getDate'). The datepicker was initialized using this code: <h4>Transaction Date:</h4> From: <input id="sta ...

Switch images when hovering

I currently have two dropdown menus called NEW and SHOP. When I hover over the New Menu 1, it should display the corresponding image. Similarly, when hovering over New Menu 2, the related image should be shown in a div with the ".menu-viewer" class. Whil ...

Prevent form submission once all tasks have been finalized

Hey there, I've been racking my brain for hours trying to solve this issue... I'm looking to disable my form after it's been submitted to prevent multiple submissions. However, every method I try seems to disable the button but also interfe ...

Tips for resizing the background to match the font size on a canvas marker in Google Maps

Check out my jsFiddle code below: var marker = new google.maps.Marker({ position: new google.maps.LatLng(-25.363882,131.044922), map: map, title:"Hello World!", icon: CanvasCrear("hola", 15) ...

Seeking guidance on navigating a Bootstrap tabbed navigation menu with nested dropdowns using previous and next buttons

My template features tabbed navigation with a nested dropdown menu. The previous and next buttons are meant to provide secondary navigation through each of the tabs. The issue arises when trying to navigate through the pages in the dropdown menu using the ...

The issue of misplaced data and nested v-for loops

I received some rather messy data from a backend API in JSON format and I am struggling to display it correctly within an HTML table. The list items are not aligned properly within the table. For instance, as shown in the screenshot, items like 2.1, 2.2, ...

Detect keypress within a BrowserWindow even when multiple BrowserView components are present

In my Electron application, I have a main BrowserWindow that contains the main user interface index.html, along with multiple BrowserView elements: browserWindow = new BrowserWindow({ width: width, height: height, frame: false }); browserWindow.webContents ...

Rearrange elements in an array

Currently, I have an array of sphere meshes and I am looking for a way to position them in a level. The meshes are currently set in a specific position (in the shape of a skeleton), but I would like to move the entire array and place it in a different loca ...

What is the process for extracting HTML content using the JavaScript executor?

import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; public class WebDriverExample { public static void main(String[] args) { System.setProperty("webdriver.c ...

Struggling to show API images on NextJS application

I am currently exploring NextJS for the first time and attempting to showcase 3 random dog breed images on my app's webpage using the Dog.ceo API. Although I can view the three random dogs in the console through the console.log(data) line, I am facing ...

Running globally installed node modules on Windows 7 is not supported

Note: Despite scouring various posts on this issue, I have not found a solution that works for me. That's why I am reaching out here. Problem: I am facing an issue while trying to set up the http-server package on my Windows 7 system using the comman ...

What is the process of sending a component as props using props in react?

Currently, I am utilizing the react-grid library provided by dev-express. Within this library, there is a Table component that allows us to pass in a Cell component. In my CustomCell component, I have integrated the Menu component from Material UI. < ...

Unable to retrieve a value from an Angular EventEmitter

Is there a way to retrieve the result of a method call between components using an EventEmitter? While I understand that there are more efficient methods such as calling the method from a service directly, my situation requires me to utilize the base compo ...

NativeScript element isn't showing up

Being relatively new to application development with NativeScript, I find myself in a situation where I need assistance in finding a solution. Drawing from my experience with PHP, I am now looking to create a template for each "page" of the application. Th ...

What is the proper method for utilizing colspan within the footerData of a jqGrid?

Are you looking to customize the footer of your jqgrid as shown in the example below? I am trying to set up a custom footer for my jqgrid similar to the one displayed above. I have already enabled the footerrow:true option and used $self.jqGrid("footerDat ...

What is the process for converting an <input type="file> into a base64 string?

Currently, I'm attempting to send an image to my express backend by including the image directly in the post request body. var imgValue = document.getElementById("image").value; Within my post request: body : JSON.stringify({ image:imgValue ...