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
One approach is to use jQuery's each method to load each of the sections into array you define prior. Setup your conditions within the each method, collect the data and do whatever your heart desires with each list.
With this method you can set as many variables within this one each method to check for. For example, if there was another attribute you wanted to check within each li element, you can do that and make more lists.
The console.log below, simply gives you a visual on what is stored within each array you define. Good Luck!
And a quick jsFiddle demo.
var cat1 = [];
var cat2 = [];
var cat3 = [];
$('li').each(function () {
var attrvalue = $(this).attr('data-category');
if (attrvalue == "category-1") {
cat1.push(attrvalue);
}
if (attrvalue == "category-2") {
cat2.push(attrvalue);
}
if (attrvalue == "category-3") {
cat3.push(attrvalue);
}
});
console.log('how many are here? :'+ cat1);
console.log('how many are here? :'+ cat2);
console.log('how many are here? :'+ cat3);