0

I'm adding lines to a div element with javascript using append:

myDiv.append("sometext <br>");

After say 20 lines, I'd like to remove the earliest line, and keep removing lines as I add new one to prevent it from getting to large. What is an easy way to do this?

Thanks.

BrTkCa
  • 4,703
  • 3
  • 24
  • 45
Gerry
  • 1,838
  • 5
  • 24
  • 32

3 Answers3

0

Since you use "append", I assume you are using JQuery, and not straight JavaScript. In that case, I would write something like:

myDiv.find(':first-child').remove();
KnightB4
  • 85
  • 8
0

The easiest way is add the text a list, to count the total and remove the first. But, if you want to do with only plain text, you can do somethinh like this.

$("button").click(function(){
  var myDiv = $("div ul");
  var text = "<li>sometext " + Math.random(2) + " </li>";
  myDiv.append(text);
  if ($("div ul li").size() > 5){
    myDiv.find(':first-child').remove();  
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<button>Add</button>

<div>
  <ul>
  </ul>
</div>
Community
  • 1
  • 1
BrTkCa
  • 4,703
  • 3
  • 24
  • 45
  • interestingly this works if you add
  • elements to the div. I was adding lines terminated by
    and that did not work. It only removed the br elements.
  • – Gerry Sep 29 '16 at 15:59