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/
here is a code that's working: use object instead of array to have key. use var instead of const to modify your variable;
const spans = document.querySelectorAll('span');
var 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));
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