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
?
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 can use a for-loop, not sure if you're including that in the "without using .each" part or not. – Shelby115 Commented Jan 5, 2015 at 1:32
- regardless of whatever method you use it will require looping over the elements – charlietfl Commented Jan 5, 2015 at 1:35
3 Answers
Reset to default 5You 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; });
var array=$('div[data-id]');//array
will store all the div containing data-id
in the order as it is appearing in your DOM.
so suppose you want to get 2nd div just do like this array[1].attr('id')