tags:

views:

1506

answers:

3

Hi guys

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

+1  A: 
if( $('#myUnorderedList > li').size() % 2  != 0 )
{
    //add an extra li somewhere
    $('#myUnorderedList').append( '<li>content</li>' );
}
Stefan Kendall
+3  A: 

I'd do it like this:

if ($('ul#my-ul > li').length %2 != 0){
    $('ul#my-ul').append('<li></li>');
}
piquadrat
ul#my-ul is redundant and slower than #my-ul.
Stefan Kendall
it is redundant, but IMHO more readable. Do you have a link that explains why it is slower? Thanks
piquadrat
Ids are unique. When you perform ul#my-ul, you invoke a search across all the elements, looking for the id. I'll find a link in a minute.
Stefan Kendall
It’s rather redundant to search for `ul` twice.
Gumbo
It is redundant, but it is not slower. jQuery uses Sizzle, which is right to left, and it makes exceptions for #id's
Mike Blandford
Fine, it may be just as fast with 1.3.x and sizzle, but that doesn't mean it's a good or right coding decision. It adds a few extra characters that minifiers should (but won't currently) parse out, and I don't think the 'ul' qualifier adds any value whatsoever to the id tag. Consider a page that uses lists all over, for navigation, display, and image cycling. "ul" does NOTHING to identify #my-ul in this case, and it makes #my-ul more obfuscated in the selection.
Stefan Kendall
+4  A: 

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.

Gumbo