简体   繁体   English

jQuery删除嵌套的ul / li

[英]jQuery remove nested ul/li

How do I use jQuery to delete all the elements under "li_1" (but not delete li_1) 如何使用jQuery删除“ li_1”下的所有元素(但不删除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 . 实际上,您所指的ul不是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. 首先修复该标记,然后尝试使用empty方法删除所有匹配元素集的所有子节点,然后使用empty方法删除所有子元素。

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 s

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

If you just want to remove the child ul then try this 如果您只想删除子ul尝试此操作

$('#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, 然后将您的JS更改为

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

Your li_1 element does not have any child as we can clearly see. 我们可以清楚地看到,您的li_1元素没有任何子级。 If you want to remove <ul id="ul_1.1"> you can simply use $('#ul_1.1').remove(); 如果要删除<ul id="ul_1.1"> ,则只需使用$('#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(); 例如,如果您具有此li元素的id ,则可以编写$('#'+id).next().remove(); .

If this is a bug in your HTML, then see ShankarSangoli answer. 如果这是HTML中的错误,请参阅ShankarSangoli答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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