Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search for divs matching two attributes?

I have a series of div elements with the class "row" and attributes data-date-month and data-date-day.

I'm looking to count the number of elements with the class row whose attributes match today's day and month.

As far as I'm aware, to search for all the div elements matching the month is as follows:

function calculateStats(){      
    var d = new Date();
    var tmon = d.getMonth() + 1;
    var tday = d.getDate();
    var numMatches = $('div.row[data-date-month="' + tmon + '"]').length;
}

The only way I understand how to accomplish this is by using $.each():

var numMatches = 0;
$('div.row[data-date-month="' + tmon + '"]').each(function(){
    if ($(this).attr('data-date-day') == tday) 
        numMatches++;
});

However, this is a very intensive function when there could potentially be hundreds of elements to scan through.

How can I search efficiently to find elements that match the day as well, or do I have to use $.each()?

like image 277
Ben Avatar asked Nov 18 '25 21:11

Ben


1 Answers

You can use two attribute selectors, like this:

var numMatches = $('div.row[data-date-month="' + tmon + '"][data-date-day="' + tday + '"]').length;

Alternatively, you can use filter():

var numMatches = $('div.row').filter(function() {
    var $el = $(this);
    return $el.data('date-month') == tmon && $el.data('date-day') == tday;
}).length;
like image 52
Rory McCrossan Avatar answered Nov 21 '25 12:11

Rory McCrossan