how to remove last child when adding new item with jquery

I like to add dinamic li with jquery. I want to remove last position li when it reach 3 and keep append when I enter new value. But I have problem to deleting last position.

Is there any suggestion how to remove last position when add new item thanks

$(document).ready(function() {
  $('.search').on('click', function() {
    var text = $('#person').val();
    var li_count = $('ul.history li').length;
    $('#person').val('');
    if (li_count < 3) {
      $('ul.history').prepend('<li><a href="' + text + '">' + text + '</a></li>');
    } else {
      $('ul.history li:last-child').remove();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="person" type="text">
<button class="search">search</button>
<ul class="history">
</ul>

Answers 1

  • You are there, always prepend the searched text and remove if condition is achieved.

    $('ul.history').prepend('<li><a href="' + text + '">' + text + '</a></li>');
    if (li_count >= 3){
      $('ul.history li:last-child').remove();
    }
    

    $(document).ready(function() {
      $('.search').on('click', function() {
        var text = $('#person').val();    
        $('#person').val('');    
        $('ul.history').prepend('<li><a href="' + text + '">' + text + '</a></li>');
        
        //Take latest length
        var li_count = $('ul.history li').length;
        if (li_count > 3){
          $('ul.history li:last-child').remove();
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="person" type="text">
    <button class="search">search</button>
    <ul class="history">
    </ul>


Related Articles