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 or tags in a news section.
For example, I would like to create something like this:
- Category 1 (5)
- Category 2 (3)
- Category 3 (1)
from this html:
<ul class="categories">
<li data-category="category-1">Category 1</li>
<li data-category="category-1">Category 1</li>
<li data-category="category-1">Category 1</li>
<li data-category="category-1">Category 1</li>
<li data-category="category-1">Category 1</li>
<li data-category="category-2">Category 2</li>
<li data-category="category-2">Category 2</li>
<li data-category="category-2">Category 2</li>
<li data-category="category-3">Category 3</li>
</ul>
How can I achieve this in jQuery? Is it even possible?
It is possible, check this jsFiddle I've created.
May be dirty, but it's what I came up with:
And, fiddle.
Example
If data attribute is on
span
ordiv
inside<tr>
then you have to usefind
.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.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.