I\'m trying to group each instance of a data attribute into a list from the number of occurrences of each attribute in a page, using jQuery. Similar to grouping categories o
If data attribute is on span
or div
inside then you have to use find
. Find
is more costly in term of DOM search. Is better to just add class on that elements where you have data-attribute and loop through and get information.
/*
* fetch labels from list by data attribute
*
*/
function fetch_labels() {
var leadssource = {},
lead;
$('#leads-list tr').each(function(i, el) {
lead = $(el).find('[data-leadsource]').data('leadsource');
if (leadssource.hasOwnProperty(lead)) {
leadssource[lead] += 1;
}
else {
leadssource[lead] = 1;
}
});
return leadssource;
}