Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of jQuery elements returned from a matched condition?

I have a jQuery filter on a set of elements that check to see which items are under the value of 90 and over 100. What I want to do is also get the number of items that match those conditions and eventually save them for output somewhere else on the page:

$("#dtarget li").filter(function()
{
    if (parseInt(this.innerText) < 90)
    {
        $(this).css("color","red");
    }
    else if (parseInt(this.innerText) > 100)
    {
        $(this).css("color","gold");
    }
});

I'm new to jQuery and Javascript, so be easy.

like image 583
Psdpainter Avatar asked Nov 30 '25 17:11

Psdpainter


1 Answers

http://api.jquery.com/length

You can call .length on a jQuery object to get the number of DOM elements it contains.

//this will return a jQuery object with elements who's value is less than 90
var less_than_90 = $("#dtarget li").filter(function()
{
    var text = $(this).text();
    if (parseInt(text) < 90)
    {
        return true;
    }
    return false;
});

//then you can get the number of DOM elements within the jQuery object created above
var less_than_90_count = less_than_90.length;

This can then be done for anything greater than 100 as well.

Notice that I removed this.innerText in favor of $(this).text() since you are already using jQuery you might as well get all you can out of it.

Here is a demo: http://jsfiddle.net/acyZC/1/

like image 149
Jasper Avatar answered Dec 03 '25 08:12

Jasper