Checking for length of ul and removing an li element
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 som开发者_Python百科ething 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:
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.
var ul = document.getElementById('myUL');
if (ul.childNodes.length > threshold)
ul.lastChild.parentNode.removeChild(ul.lastChild);
Hope that helped.
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!
精彩评论