stackbaz stackbaz - 2 months ago 6
jQuery Question

Appended later elements not remove

I wrote below code to append 5 li when i click on add button but the problem is with remove button, when i click on remove button i want to remove last 5 recent lis . but it does not work.
here is my snippet :



$(document).ready(function () {
$(".moree").click(function () {
var delay = 0;
for (var i = 0; i < 5; i++) {
$(this)
.prev()
.append('<li style="display:none">Title 2</li>')
.children()
.last()
.hide()
.delay(delay)
.slideDown(400);
delay += 400;
}
});

$(".remove").click(function () {
$(this)
.parents('ol').remove()
.slideUp(400);

});

});

ol > li{ list-style:none; padding-top:10px; border:1px solid green;margin-top:10px;}
.moree{ width:30px; background:yellow;}.remove{ width:30px; background:red;}

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
</head>
<body>
<div class="content">
<ol>
<li>title</li>
</ol>
<div class="moree">Add 5</div>
<div class="remove">Remove 5</div>
</div>
</body>
</html>





Thanks

Answer

The ol is not a parent of the .remove button. You need to amend your traversal logic slightly.

To get the last 5 elements, use .slice(-5). Also, if you remove() the elements before you call slideUp() they will just vanish. You need to call slideUp() first. Try this:

$(document).ready(function() {
  $(".moree").click(function() {
    var delay = 0;
    for (var i = 0; i < 5; i++) {
      $(this).prev().append('<li style="display: none">Title 2</li>').children().last().delay(delay).slideDown(400);
      delay += 400;
    }
  });

  $(".remove").click(function() {
    $(this).closest('.content').find('ol li').slice(-5).slideUp(400, function() {
      $(this).remove();
    });
  });
});
ol > li {
  list-style: none;
  padding-top: 10px;
  border: 1px solid green;
  margin-top: 10px;
}
.moree {
  width: 30px;
  background: yellow;
}
.remove {
  width: 30px;
  background: red;
}
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
  </script>
</head>

<body>
  <div class="content">
    <ol>
      <li>title</li>
    </ol>
    <div class="moree">Add 5</div>
    <div class="remove">Remove 5</div>
  </div>
</body>

</html>