4

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?

2
  • You can use a for-loop, not sure if you're including that in the "without using .each" part or not. Commented Jan 5, 2015 at 1:32
  • regardless of whatever method you use it will require looping over the elements Commented Jan 5, 2015 at 1:35

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Nice. Do you know anything about the efficiency of map vs. a loop?
loop will always be faster, but if you're not going through thousands of elements, it's not gonna matter
2

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; });

Comments

0

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.