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.
It is common to cache the results of your selector. Here, you can search for the
<li>s directly:In this case you can also achieve this with a single selector:
That is: Among all
<li>with index greater than 4 (or your threshold), select the last and remove it.