The wrapAll() method can be used to wrap list items within two columns

I am looking to group multiple li elements within two div containers by using jQuery's wrapAll method. The challenge lies in the fact that these items are rendered within a single <ul> element via a CMS. Here is the current setup:

<ul>
    <li class="list-1">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
        <li class="list-2">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
        <li class="list-3">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
        <li class="list-4">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
</ul>

The goal is to group list-1 and list-2 within one div, and list-3 with list-4 into another div. This way, we achieve the following result:

<ul>
    <div class="group-1">
        <li class="list-1">
            <span>1</span>
            <span>2</span>
            <span>3</span>
        </li>
            <li class="list-2">
            <span>1</span>
            <span>2</span>
            <span>3</span>
        </li>
    </div>
    <div class="group-2">
        <li class="list-3">
            <span>1</span>
            <span>2</span>
            <span>3</span>
        </li>
            <li class="list-4">
            <span>1</span>
            <span>2</span>
            <span>3</span>
        </li>
    </div>
    </ul>

I am exploring if it's possible to use something like this:

$( "li:nth-child(1), li:nth-child(2)" ).wrapAll( "<div class='group-1'></div>" );

Any suggestions or guidance on achieving this would be greatly appreciated!

Answer №1

You can use the following function to group elements in li tags.

To adjust the grouping, simply update the value of the groupSep variable as needed.

For this example, I have set groupSep = 2.

Check out the demo below:

$(document).ready(function() {
  var groupCounter = 1;
  var groupSep = 2;
  var liHtml = '';
$('ul > li').each(function(index, el){
    if(((index+1) % groupSep) === 1){
      $('ul').append('<div class="group-'+groupCounter+'"></div>');
      for(i=0; i<groupSep; i++){
        $('ul > li').eq(0).appendTo('ul .group-'+groupCounter);
      }
      groupCounter++;
    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
    <li class="list-1">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
        <li class="list-2">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
        <li class="list-3">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
        <li class="list-4">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
      <li class="list-5">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
      <li class="list-6">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
      <li class="list-7">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
      <li class="list-8">
        <span>1</span>
        <span>2</span>
        <span>3</span>
    </li>
</ul>

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 for me to develop a mobile application using JavaScript, HTML, and CSS and distribute it for sale on the App Store, Google Play Store, and Microsoft Mobile App Store at

I have a keen interest in web standards such as Javascript, HTML, and CSS. My goal is to utilize these languages to develop applications for mobile devices like phones and tablets. I am also considering selling these applications on various platforms inclu ...

The value of the second select box will automatically update when the first select box is changed, and vice

If the 1st box is selected, the second box will change and vice versa. echo '<td><select id=hello name=hello onchange=my()>'; while($fet=mysql_fetch_assoc($sql1)) { echo "<option value=".$fet['username'].">".$fet[&ap ...

Why isn't the KO Array binding being implemented?

Hello, I am experiencing an issue with KO array bindings not being applied properly. Below is the code snippet causing the problem: var movements_array = []; var viewModel = { movements: ko.observableArray(movements_array), }; $(document).ready(func ...

Choosing the fourth cell in every row of a table and converting the information

Currently, I am working on a function that is supposed to take the fourth column in each row of a specific table, manipulate the data using a function, and return different data for the cell. This function takes an integer representing total minutes as i ...

Enter key triggering input change event is unresponsive in Internet Explorer

$("#inputBoxWidth").change(function() { var curValue = $("#inputBoxWidth").val(); alert(curValue); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="text" id="inputBo ...

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 ...

What is the reason behind opting for ng-style over style in AngularJS for applying CSS formatting?

Recently, I've delved into AngularJS and have been exploring its depths for a few days now. I'm curious about the use of ng-style in styling components within both static and dynamic webpages. Given that we already have the traditional style tag ...

Steps to displaying the functions linked to a Jquery element

Currently diving into the realm of JQuery, I am on a quest to discover a method to access and view the associated methods of an object once it has been created, reminiscent of python's dir() function. ...

Leveraging partials on their own

I am currently exploring the possibility of loading a partial in linkedin-dustjs without having to load its parent along with it. For instance, consider this partial (login.dust): {>layout/} {<content} <!-- Login Screen --> {/content} Th ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

Vue modifies the array in the data after creating a duplicate of it

Here is the Vue code snippet I'm working with: export default { name: 'Test', data() { return { test1: ['1', '2', '3'], test2: [{ name: 'Hello' }, { name: &apo ...

Tips for concealing overlay when the cursor hovers

Can anyone help me with a code issue I'm having? I want to hide an overlay after mouse hover, but currently it remains active until I remove the mouse from the image. Here is the code: .upper {position: absolute; top: 50%; bottom: 0; left: 50%; tra ...

Uncovering website content with Selenium: unlocking the mysterious origins of the text

Currently, I am utilizing Selenium and Python to scrape a website. My goal is to extract specific text from a particular page. Despite successfully navigating to the desired page, every attempt at using methods such as driver.find_elements_by_id(), driver. ...

What could be causing AngularJS to truncate my URL in the search bar?

Currently, I am in the process of setting up a state provider for a CRUD website. One issue I encountered is that when I navigate to www.mysite.com/posts/mypost, the URL gets shortened to www.mysite.com/mypost and does not trigger the controller as intend ...

I ran into an issue trying to generate a React app using the command "npx create-react-app" and was unable to proceed

When I attempted to run the command npx create-react-app my-app, I encountered an error: (ps: I also tried running npm init and npm install create-react-app before executing the aforementioned command, but still got the same error.) HELP! Installing pack ...

Exploring the potential of Angular JS and gapi in building a seamless routed

I'm facing a similar challenge as described in this question. However, the key difference is that I require two controllers for two distinct routes, essentially representing two different tables: ../table1 and ../table2. Each table needs to fetch data ...

Having trouble with VueJS ref not preventing the default form action on submit?

Within my <script> tag, I currently have the following code: render(createElement) { return createElement("form", {ref: "formEl" , on: {submit: this.handleSubmit} }, [ <insert create form inputs here> ]); } handleSubmit(e) { ...

The delete_node() function in jstree does not seem to be removing nodes

In my attempt to create a custom context menu for different nodes, I've managed to display different labels for clicks on folders or files. However, I am facing some challenges when trying to delete them. Take a look at my code snippet. Due to diffic ...

Using jQuery to replace the content of a div with a delay?

I am attempting to utilize jQuery to create a fade effect on an element, replace its innerHTML content, and then fade it back in once the new content has been added. I have successfully managed to replace the element's content using the .html() method ...

Error encountered while utilizing MUI Button: Unable to access property 'borderRadius' from an undefined source

import React, { Component } from 'react'; import './App.css'; import Screen from './components/Screen/Screen'; import Button from './components/Button/Button'; import { MuiThemeProvider, createMuiTheme } from 'm ...