I have a few spans:
<span class="first" data-id="1" />
<span class="second" data-id="4" />
<span class="second" data-id="2" />
<span class="third" data-id="5" />
And operations on them:
const spans = document.querySelectorAll('span');
const list = [];
spans.forEach(function(span) {
if (typeof list[span.getAttribute('class')] === 'undefined') {
list[span.getAttribute('class')] = [];
}
list[span.getAttribute('class')].push(span.getAttribute('data-id'));
});
console.log(list);
console.log(JSON.stringify(list));
But JSON.stringify return empty array.
How can I count the number of occurrences of data-id at a given SPAN the easiest way and next get it to string? I would like to send this data to API.
Fiddle: https://jsfiddle.net/x7thc59v/
const list = {}JSON.stringify will return empty array for any not number indexes. And you can useconst obj = {}instead of list since you don't want list you want object.