Question

I quickly made this function for a script im using:

$.fn.liCount = function(){
    var i=0;
    $(this).children().each(function(){
        i++;
    });
    return Number(i);
}

problem is IE returns 0, anyone know why?

alert( $("ul").liCount() );

edit:

<div id="prev-quotes">
    <ul id="quote-list">
        <li id="quote_content_wrapper" >
            <ul>
                <li class="quote_li">
                    <span class="service_quote"><a href="#">Web Design Services</a></span>
                    <br>
                    <span class="cost_quote"><strong>£192</strong> - <a id="7" href="#">delete</a> | <a id="7" href="#">view</a></span>
                </li>
                <li class="quote_li">
                    <span class="service_quote"><a href="#">Web Design Services</a></span>
                    <br>
                    <span class="cost_quote"><strong>£192</strong> - <a id="7" href="#">delete</a> | <a id="7" href="#">view</a></span>
                </li>
                <li class="quote_li">
                    <span class="service_quote"><a href="#">Web Design Services</a></span>
                    <br>
                    <span class="cost_quote"><strong>£192</strong> - <a id="7" href="#">delete</a> | <a id="7" href="#">view</a></span>
                </li>
            </ul>
        </li>
        <li>
            <a id="first-quote" href="#">Previous Quotes</a>
            <img height="16" width="16" id="warning" src="images/for_web/check_mark.png">
        </li>
    </ul>    
</div>
Was it helpful?

Solution

You can simply use

$("ul > li").length;

See Child Selector (“parent > child”)

If you want to get the number of li inside ul with id quote-list, you can use

$("#quote-list > li").length;

If you want to get the number of li with class names quote_li, you can use

$("#quote-list > li > ul > li.quote_li").length;

OTHER TIPS

There’s no need to use return Number(i); when you’re certain i is a number.

You don’t even need a counter var at all — there’s .length in jQuery.

Why not just use the following instead:

$.fn.liCount = function() {
 return $(this).children('li').length;
};

It’s shorter, faster, more readable, and it works in all browsers.

However, it seems a little verbose / unnecessary to write a ‘plugin’ for this. You could just use something like:

$('ul > li').length;

In IE 7 and 8 you need to identify the child tag

$.fn.liCount = function(){
    var i=0;
    $(this).children("li").each(function(){
        i++;
    });
    return Number(i);
}

will work. Of course this limits the use of the method unless you pass in the element you wish to count like...

    $.fn.liCount = function(elem){
        var i=0;
        $(this).children(elem).each(function(){
            i++;
        });
        return Number(i);
   }

then call

alert( $("ul").liCount("li") );

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top