views:

49

answers:

3

I am trying to remove the last <li> element from a <ul> element only if it exceeds a particular length. For this, I am doing something like this:

var selector = "#ulelement"
if($(selector).children().length > threshold) {
   $(selector + " >:last").remove();
}

I don't like the fact that I have to use the selector twice. Is there a shorter way to do this? Something like a "remove-if-length-greater-than-threshold" idea. I was thinking that maybe there is a way to do this using the live() function but I have no idea how.

+2  A: 
var ul = document.getElementById('myUL');
if (ul.childNodes.length > threshold)
  ul.lastChild.parentNode.removeChild(ul.lastChild);

Hope that helped.

Delan Azabani
@Delan: +1 for the answer. Out of curiosity, I was just looking for a jquery based solution but thanks anyways.
Legend
+1  A: 
selector = '#ulelement';
while($(selector).children().length > threshHold)
{
     $(selector + " li:last").remove();
}

Try using a while loop, as your code only runs once, the while will loop untill its less than thresh hold!

RobertPitt
If I understood well, Legend only wants to remove the last item, not every item above threshold. And in the latter case, I'd use li:gt() instead of li:last
Felipe Alsacreations
@RobertPitt: +1 for the while construct as well. Thanks for your time.
Legend
no problem, my understanding if the Lists element is greater then the threshold then he wishes to remove all elements that are pushing the list above that threshold so that the list is the correct height on the webpage.as im using remove() and not hide() the element disappears so that when the loop starts again it has a new length etc etc
RobertPitt
+6  A: 

It is common to cache the results of your selector. Here, you can search for the <li>s directly:

var lis = $("#ulelement li");
if(lis.length > threshold) {
   lis.eq(lis.length - 1).remove();
}

In this case you can also achieve this with a single selector:

$("#ulelement li:gt(4):last").remove();

That is: Among all <li> with index greater than 4 (or your threshold), select the last and remove it.

Kobi
Amazing.. Thanks a lot.
Legend
+1 Common and suggested
Justin Johnson
Saves a while loop, and very effective +1
RobertPitt