jQuery - how to count the number of li and add one if the number is odd?

advertisements

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.