Say I have some of divs.
<div data-id="1"></div>
<div data-id="2"></div>
<div data-id="3"></div>
<div data-id="4"></div>
Is there a way to get an array of the data-id
attribute: ["1", "2", "3", "4"]
without using .each
?
You could use .map()
: (example here)
var array = $('div[data-id]').map(function(){
return $(this).data('id');
}).get();
console.log(array);
Alternatively, using pure JS: (example here)
var elements = document.querySelectorAll('div[data-id]'),
array = [];
Array.prototype.forEach.call(elements, function(el){
array.push(parseInt(el.dataset.id, 10));
});
console.log(array);
...or using a regular for-loop: (example here)
var elements = document.querySelectorAll('div[data-id]'),
array = [],
i;
for (i = 0; i < elements.length; i += 1) {
array.push(parseInt(elements[i].dataset.id, 10));
}
console.log(array);
You could use a for loop and do it without JQuery even, in case you are looking for a more primitive solution, like:
var nodes = document.querySelectorAll('[data-id]');
for(var i=0;i<nodes.length;i++){
// do something here with nodes[i]
}
Or to optain an array directly from your query result you could also use Array.prototype.map.call
:
var values = Array.prototype.map.call(nodes, function(e){ return e.dataset.id; });
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