简体   繁体   中英

How to append li inside new div

I have a HTML markup like this:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>
</ul>

How can I convert above HTML into this:

<div class="main"><ul><li>Item 1</li><li>Item 2</li></ul></div>

<div class="main"><ul><li>Item 3</li><li>Item 4</li></ul></div>

<div class="main"><ul><li>Item 5</li><li>Item 6</li></ul></div>

<div class="main"><ul><li>Item 7</li><li>Item 8</li></ul></div>

You can do like this:

$('ul > li:nth-child(2n-1)').each(function() {
    $(this).next().add(this).wrapAll('<div class="main"><ul></ul></div>');
}).eq(0).closest('div').unwrap();

Working Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM