skip to Main Content

I am using socket.io and twitter streaming API.

Now I have to keep the recent three tweets in a list

<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>

My Question is how to do this in Jquery? Whenever there is a new tweet I want to insert it in to first li and move the first li tweet in to second li and so on and remove the 4th tweet.

2

Answers


  1. Use .prepend() method in jQuery. This adds HTML element as the first node of the target.

    $("ul").prepend("<li>new item</li>");
    

    And as @Kartikeya suggested, remove the last one like:

    $("ul > li:last").remove();
    
    Login or Signup to reply.
    • Use .prepend to insert new element at the beginning of the target element.
    • Use :gt() to remove the element if length is greater than expected
      length.
    var count = 0;
    $('button').on('click', function() {
      var li = '<li>Data New' + count + '</li>';
      ++count;
      $('ul').prepend(li);
      if ($('ul li').length > 3) {
        $('ul li:gt(2)').remove();
      }
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <ul>
      <li>Data</li>
      <li>Data</li>
      <li>Data</li>
    </ul>
    <button>Add</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search