Grow your CSS skills. Land your dream job.

Counting list items in each TD with jQuery?

  • # December 15, 2011 at 7:47 pm

    Within each TD of the retailers div there is a UL, what I am trying to do is determine how many list items exist in each individual TD, if there is more than 1 list item I need to style it a specific way, as you can see below, however, when trying this code it applies the CSS to every LI, I am not sure where I am going wrong?

    	$('#retailers tr').each(function()
    {
    $.each(this.cells, function()
    {
    var countLI = $("ul.links").children().length;

    if(countLI + ":gt(1)")
    {
    $("ul.links li").css("background-color", "yellow");
    }
    });
    });
    # December 16, 2011 at 2:09 am

    Can you put the example into a fiddle @ jsfiddle.net?

    # December 16, 2011 at 8:01 am

    Just from a quick glance at the code, “:gt(1)” is a jQuery selector and shouldn’t be used in a numerical comparison. Try this:

            $('#retailers tr').each(function()
    {
    $.each(this.cells, function()
    {
    var countLI = $(this).find("ul.links").children();

    if(countLI.length > 1)
    {
    countLI.css("background-color", "yellow");
    }
    });
    });
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".