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

Importing information from the Document Object Model in Vue.js, focusing on the action attribute of a form

Can Vue be used to create a binding where the data item in the Vue instance is initialized from the DOM? In my specific case, I want my Vue instance to receive the action attribute of a form element. For example, this is how my HTML would look like (the ...

Retrieving the XML data from an uploaded file using PHP

How can I upload an XML file to my server and extract its content? Step 4: Writing each row from the XML file into a database. This is my current attempt: xml_import.php <?php if(isset($_POST["submit"])){ echo "Let's test"; $uploaddir ...

Ways to initiate the download of an audio link using JS without the need for the browser to redirect to a different page

I am looking to create a script that can automatically download audio files from a website. The problem I'm encountering is that using element.click() to simulate a "click" event doesn't work as expected, as the browser ends up navigating to the ...

Ways to reduce lag while executing a for loop

How can I optimize my prime number generation process to avoid lagging? For example, is there a way to instantly display the results when generating primes up to 1000? HTML: <!DOCTYPE html> <html> <meta name="viewport" content="width=dev ...

Error in Node.js (NPM Error)

Recently, I purchased a VPS running Ubuntu 14.4 and successfully installed Node.js 1.4. However, when attempting to run my script (node tradebot.js), I encountered the following error message! :-/ module.js:327 throw err; ^ Error: Cannot find ...

What are the options for app directory routing and programmatic navigation in the upcoming 13 application

I am currently working on a project called Next 13 that involves using the app directory and MUI 5. The project's structure is organized as follows: ./src ./src/app ./src/app/dc ./src/app/dc/admin ./src/app/dc/admin/dc_types.jsx However, when I try t ...

Adjust the size of the mat-expansion indicator to your desired height and width

Trying to modify the width and height of the mat indicator has been a bit challenging. Despite following suggestions from other similar questions, such as adjusting the border width and padding, I am still unable to see the changes reflect in my CSS file ...

What is the best way to have the text in my table cell wrap when it reaches the width of the image in the same cell?

Within the table, I have <td> elements structured like this: <tr> <td> <p class="tableText">Lengthy random text..........</p> <img src="www.imageurl.com/img.png" width="33vw"> </td> &l ...

Using jQuery, you can easily modify the color of a TD cell by applying the css properties assigned to the div element

I am attempting to implement a jQuery script that will execute upon the loading of the document. The objective is for the script to retrieve the background color of a div located within a td cell and apply it as the background color for the respective td c ...

Is there a way to emphasize text within a string of object array items?

I am currently utilizing the data provided below to pass as props in React. The functionality is working smoothly, but I have a specific requirement to only emphasize the words "target audience" within the text property. Is there a feasible way to achieve ...

Navigating through a large number of distinct items in Three.JS

I have hit a roadblock in my project development. I am striving to create a level using various phong materials on objects of unique sizes and shapes. However, Three.JS's default texture handling causes them to stretch out and look distorted on meshes ...

A custom JavaScript function designed to replicate Excel's functionality of dividing numbers by thousands

I've noticed a unique behavior in Excel where when a cell is in focus and you enter, for example, 1500.32, it displays as 1 500.32. However, once you click enter or move away from the cell, it changes to 1 500.32. I'm intrigued by how this works. ...

Trouble persisting values with Heroku due to variable issues

Here is a concise example: let value = null; const getValues = () => { fetch('/third-party-api') .then(res => res.json()) .then(data => { value = data; }) } getValues(); app.get("/values", async (req, res) ...

Using Jquery to store input values from within <td> elements in an array

I'm trying to capture user input from a dynamically changing table with 2 columns. How can I retrieve the data from each column separately? The size of the table is adjusted by a slider that controls the number of rows. Below is the structure of my ta ...

Changing an array into a list using javascript

function convertArrayToList(inputArray) { let list = null; for (let i = inputArray.length - 1; i >= 0; i--) { list = { value: inputArray[i], rest: list }; } return list; } let result = convertArrayToList([10, 20]); console.log(JSON.stringi ...

Node.js removes leading zeroes from dates

I am looking to generate a string with the current date and time in the format: "2021-06-02 09:37:38" const today = `${new Date().toLocaleDateString('sv-se')} ${new Date().toLocaleTimeString('sv-se')}`; console.log(today); ...

New ways to style Links in NextJs 13

I am relatively new to Next.js and I am attempting to create a menu with a hover effect using the following code: import Link from 'next/link'; const MenuItem = ({ href, label }) => ( <Link href={href} className="menu-item"> ...

Using jQuery to remove the 'active class' when the mouse is not hovering

I recently came across this amazing jQuery plugin for creating slide-out and drawer effects: However, I encountered a problem. I want to automatically close the active 'drawer' when the mouse is not hovering over any element. The jQuery plugin c ...

Ui-router experiencing issues with nested view loading due to changes in URL

I have been developing an application and previously used ui-router successfully with Ionic. The issue I am facing now is that although the URL changes correctly as expected, nothing happens afterwards. I am certain that the template is being found because ...

Using npm-installed cesium for the web browser is a straightforward process that involves importing

Exciting news - Cesium is now available on npm! Once I've run npm install cesium in my project, all the codes are placed inside the node_modules folder. In the introductory hello world example of Cesium, it imports cesium similar to this: <script ...