简体   繁体   中英

jQuery remove nested ul/li

How do I use jQuery to delete all the elements under "li_1" (but not delete li_1)

<ul id="ul_1">
   <li id="li_1">1.1    //want to delete all its child elements
      <ul id="ul_1.1">    
          <li id="li_1.1.1">1.1.1</li>
          <li id="li_1.1.2">1.1.2
              <ul id="ul_1.1.2">
                 <li id="li_1.1.2.1">1.1.2.1</li>
                 <li id="li_1.1.2.2">1.1.2.2</li>
              </ul>
          </li> 
      </ul>
   </li>
   <li id="li_2">1.2</li>
   <li id="li_3">1.3</li>
</ul>

May be your markup has a bug. Actually the ul which you are referring is not a child of li_1 . First fix the mark and try this code to delete all its children using empty method which removes all child nodes of the set of matched elements from the DOM.

Markup change

<ul id="ul_1">
   <li id="li_1">1.1  //want to delete all its child elements
      <ul id="ul_1.1">    
          <li id="li_1.1.1">1.1.1</li>
          <li id="li_1.1.2">1.1.2
              <ul id="ul_1.1.2">
                 <li id="li_1.1.2.1">1.1.2.1</li>
                 <li id="li_1.1.2.2">1.1.2.2</li>
              </ul>
           </li>
      </ul>
   </li>  
   <li id="li_2">1.2</li>
   <li id="li_3">1.3</li>
</ul>

Js

$('#li_1').empty();//will empty everything from this li element

If you just want to remove the child ul then try this

$('#li_1 > ul').remove();

Your markup is incorrect, You should change your markup something like below,

<ul id="ul_1">
   <li id="li_1">1.1    //want to delete all its child elements
      <ul id="ul_1.1">    
          <li id="li_1.1.1">1.1.1</li>
          <li id="li_1.1.2">1.1.2</li>
              <ul id="ul_1.1.2">
                 <li id="li_1.1.2.1">1.1.2.1</li>
                 <li id="li_1.1.2.2">1.1.2.2</li>
              </ul>
      </ul>
   </li>               // <-- Moved your sublist #ul_1.1 inside the li #li_1
   <li id="li_2">1.2</li>
   <li id="li_3">1.3</li>
</ul>

And change your JS as,

$('#li_1 ul').remove();

Your li_1 element does not have any child as we can clearly see. If you want to remove <ul id="ul_1.1"> you can simply use $('#ul_1.1').remove(); . It will remove this element and all of its children (actually they are part of the element).

You can use some automatization. For example if you have id of this li element, then you can write $('#'+id).next().remove(); .

If this is a bug in your HTML, then see ShankarSangoli answer.

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