简体   繁体   中英

Wrapping <li> with <ul> until next header in JQuery

How can I wrap li with ul until the next h3 ?

Here is my code:

 thisContent.find("li").each(function() { $(this).nextUntil("h3").andSelf(); }).wrap('<ul></ul>');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3> Title 1 </h3> <li> List 1 </li> <li> List 2 </li> <li> List 3 </li> <li> List 4 </li> <h3> Title 2 </h3> <li> List 1 </li> <li> List 2 </li> <li> List 3 </li> <li> List 4 </li>

This is what I expect it to be:

 <h3> Title 1 </h3> <ul> <li> List 1 </li> <li> List 2 </li> <li> List 3 </li> <li> List 4 </li> </ul> <h3> Title 2 </h3> <ul> <li> List 1 </li> <li> List 2 </li> <li> List 3 </li> <li> List 4 </li> </ul>

Use wrapAll() .

Otherwise, you'll wrap each item individually. You also need to start from h3 , rather than li , because you're looking to wrap things between h3 .

jQuery('h3').each(function(){
    $(this).nextUntil('h3').wrapAll('<ul></ul>')
})

 jQuery('h3').each(function() { $(this).nextUntil('h3').wrapAll('<ul class="potato"></ul>') })
 .potato { background-color: yellow; border-radius: 1em; margin: 1em; padding: 1em 2em; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3> Title 1 </h3> <li> List 1 </li> <li> List 2 </li> <li> List 3 </li> <li> List 4 </li> <h3> Title 2 </h3> <li> List 1 </li> <li> List 2 </li> <li> List 3 </li> <li> List 4 </li>

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