1
2...">

How to remove div if graph is larger than x with jquery?

I have this html:

<div class="test">
   <div class="itsme">1</div>
   <div class="itsme">2</div>
   <div class="itsme">3</div>
   <div class="itsme">4</div>
</div>

      

and i am adding a new div dynamically with ajax call at the top of div1.

var count = jQuery('div.itsme').size();
if(count > 3){
   $('.test').find("div:last").remove();
}

      

it works so that if I add one div the last one is removed, but it doesn't actually keep track of how many divs.

Even if there are 10 divs at the beginning, as soon as I add another, the last one is removed.

Why I am looking, it should always be, in this case 3 divs are displayed. If I add another div, the last one is removed, if I add 2 divs, then the last 2 are removed

I hope I'm clear enough.

thank,

ps I'm using size()

because it lenght()

doesn't seem to work, chrome sees it as an undefined function and I checked, I have jquery 1.7 ..

+3


source to share


5 answers


if($('.itsme').length > 3){
   $('.itsme:gt(2)').remove();
}

      



FIDDLE

+7


source


You can use a selector :gt

to filter items above a certain index and remove them. This will only contain the first three elements:



$('.test .itsme:gt(2)').remove();

      

+7


source


You can just repeat like this:

var count = jQuery('div.itsme').size();
if (count > 3) {
  var numTimes = count - 3;
  for (var i = 0; i < numTimes; i++) {
    $('.test').find("div:last").remove();
  }
}

      

+2


source


You can select the last div with this selector

$('.itsme').eq(-1).remove();

$('.itsme') // select all the class

eq(-1) // select one element from the array of class begin for the end.

      

Edit:

If you want to remove all div minus the first three classes, use this:

for( var i=0; i< $('.itsme').length - 3; i++){
     $('.itsme').eq(-1).remove();
}

      

+2


source


because you only delete the last

try this:

jQuery('div.itsme:gt(2)').remove() // it starts at index 0

      

+2


source







All Articles