Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create array of certain attribute from a list of elements using jQuery

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?

like image 935
tachyonflux Avatar asked Mar 18 '23 11:03

tachyonflux


2 Answers

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);
like image 186
Josh Crozier Avatar answered Mar 20 '23 01:03

Josh Crozier


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; });
like image 43
Dalorzo Avatar answered Mar 20 '23 01:03

Dalorzo