简体   繁体   中英

insert <ul></ul into few <li>s with jQuery

Here is sample code:

<ul id="ul-1" class="ul">
    <li class="group">A</li>
    <li class="group">B</li>
    <li id="c1" class="group c">C1</li>
    <li id="c2" class="group c">C2</li>
    <li id="c3" class="group c">C3</li>
</ul>

Here is what I want to achieve with jQuery 1.4:

<ul id="ul-1" class="ul">
    <li class="group">A</li>
    <li class="group">B</li>
    <ul class="group-c">
          <li id="c1" class="group c">C1</li>
          <li id="c2" class="group c">C2</li>
          <li id="c3" class="group c">C3</li>
    </ul>
</ul>

Basically I want to group some of the list items into another group.

Here what's I have tried:

<script type="text/javascript">
     jQuery(document).ready(function($) {
         $("#c1").insertBefore("<ul class='group-c'>");
         $("#c3").insertAfter("</ul>");
     });
</script>

<script type="text/javascript">
     jQuery(document).ready(function($) {
         $("#c1").insertBefore("<li class='group-c'>");
         $("#c3").insertAfter("</li>");
     });
</script>

This would be the answer to your question:

$('li.group.c').wrapAll("<ul class='group-c'></ul>");

BUT that would resolve in some invalid html since the ul cannot be a direct child of another ul so you have to use this:

$('li.group.c').wrapAll("<li class='group-c'>C<ul></ul><li>");

Demo

 $('li.group.c').wrapAll("<li class='group-c'>C<ul></ul><li>");
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="ul-1" class="ul"> <li class="group">A</li> <li class="group">B</li> <li id="c1" class="group c">C1</li> <li id="c2" class="group c">C2</li> <li id="c3" class="group c">C3</li> </ul>

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