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()?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With