Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

like image 949
Marlon Creative Avatar asked Sep 24 '09 14:09

Marlon Creative


3 Answers

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.

like image 119
Gumbo Avatar answered Jan 02 '23 03:01

Gumbo


I'd do it like this:

if ($('ul#my-ul > li').length %2 != 0){
    $('ul#my-ul').append('<li></li>');
}
like image 35
Benjamin Wohlwend Avatar answered Jan 02 '23 04:01

Benjamin Wohlwend


if( $('#myUnorderedList > li').size() % 2  != 0 )
{
    //add an extra li somewhere
    $('#myUnorderedList').append( '<li>content</li>' );
}
like image 37
Stefan Kendall Avatar answered Jan 02 '23 05:01

Stefan Kendall