How do I search for divs matching two attributes?
I have a series of elements div
with class "string" and attributes data-date-month
and data-date-day
.
I want to count the number of items with a class row
whose attributes are for today and month.
As far as I know, searching for all items div
matching the month looks like this:
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 to figure out how to do this is to use $.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 feature where there could potentially be hundreds of items to scan.
How can I efficiently search for items that match the day, or do I need to use $.each()
?
source to share
You can use two attribute selectors, for example:
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;
source to share