Need a little help again. Say I have an unordered list, and I want it to always have an even number of li's in it. How can I use jQuery to count the number of li's, and add one blank one at the end, if the number is odd?
If you're wondering why, I have a dropdown where the "ul li ul" is twice the width of the "ul li ul li" so the dropdown li's show in 2 columns. So, purely for visuals, it would be nice to always have an even amount, even if one is blank.
Cheers
Try this:
$("ul").each(function() {
var elem = $(this);
if (elem.children("li").length % 2 != 0) {
elem.append("<li></li>");
}
});
This should add one list item to every unordered list with an odd number of list items.
I'd do it like this:
if ($('ul#my-ul > li').length %2 != 0){
$('ul#my-ul').append('<li></li>');
}
if( $('#myUnorderedList > li').size() % 2 != 0 )
{
//add an extra li somewhere
$('#myUnorderedList').append( '<li>content</li>' );
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With