开发者

How to remove <li></li> from ul?

开发者 https://www.devze.com 2022-12-09 20:30 出处:网络
how to remove a particular <li></li> from the ul list? i am adding it dynamically... and i need to remove it when th开发者_StackOverflow中文版e user click on clear. how can i do that?That

how to remove a particular <li></li> from the ul list? i am adding it dynamically... and i need to remove it when th开发者_StackOverflow中文版e user click on clear. how can i do that?


That depends on what you have and what you're adding. Assuming you end up added items so it looks like this:

<ul id="list">
  <li><a href="#" class="clear">clear</a></li>
  <li><a href="#" class="clear">clear</a></li>
  <li><a href="#" class="clear">clear</a></li>
</ul>

then use remove() to remove a single item:

$("#list a.clear").click(function() {
  $(this).parent().remove();
  return false;
});

but if you have:

<ul id="list">
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>
<a href-"#" id="clear">Clear</a>

and you want to clear all of them then use empty():

$("#clear").click(function() {
  $("#list").empty();
  return false;
});


$('li').remove();

Will remove all the li elements... I suggest you give it an id attribute when you add it so that you know which one you'll want to remove, then select it specifically with:

$('#my_li').remove();


Put a unique value into the elements id attribute when you write it. You then have a known unique referrence point from which to target that element for later manipulation.


 var ul = document.getElementById("yourElementId");

 while (ul.firstChild)
     ul.removeChild(ul.firstChild);


Use this for deleting all lis:

$("#Your_ul_Id").children().remove()

Use eq(index_of_your_li) for deleting a li:

$("#Your_ul_Id:eq(1)").remove()

Use .not("#Your_li_Id") for deleting all lis except one:

$("#Your_ul_Id").children().not("#Your_li_Id").remove()
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号