How can I limit the amount of text in a DIV that I periodically add messages to?

I have a web based program that receives one line text messages periodically from the server (with Node.js and that I append to a scrolling DIV. The messages are simple text; for example, "Input switch failed".

socket.on('statusMessage', function (newMessage) {
  $('#statusMessageDiv').append(newMessage + "<br>");

How can I remove older messages when new ones come in, so I can limit the messages displayed to the last 200 or so?



Wrap the messages in an element, count the elements, and if more than 200, remove the last appended (the first one) :

socket.on('statusMessage', function (data) {
    $('<p />', {text : newMessage}).appendTo('#statusMessageDiv');

    if ( $('p', '#statusMessageDiv').length > 200 )
        $('p', '#statusMessageDiv').first().remove();

What about

$("#statusMessageDiv span:gt(200)").remove() (Might be 199 as zero based!)

Assuming statusMessageDiv contains <span> tags. This assumed that the oldest ones are at the bottom of the pile.

Example fiddle of basic principle:

Edit: Updated fiddle with removing first/last items:


Or you could have a javascript array as a datastructure containing the string values of the messages. Do an ajax call to get the new messages with a JSON result as an array of the new messages. Splice the datastructure array with the count of the JSON result array to remove the needed items. Then add the new items to the datastructure array. And then using a library like KnockoutJS or AngularJS bind your Div to the datastructure. That way when you add and remove new items to the datastructure, your rendering div will show accordingly.


If you need to keep your existing structure then what you are trying to remove by is the first line with each additional line. The "first line" is made up of two nodes -- a text node and br node. So we can filter those out as we append the newMessage


socket.on('statusMessage', function (newMessage) {    
    var i = 0;        
    $('#statusMessages').append(newMessage + "<br/>")
    .filter(function () {
        return i <= 2 ? this : false; // 2 because one text node and one br node
}); // end on statusMessage


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.