最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create array of certain attribute from a list of elements using jQuery - Stack Overflow

programmeradmin1浏览0评论

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?

Share Improve this question asked Jan 5, 2015 at 1:31 tachyonfluxtachyonflux 20.2k7 gold badges51 silver badges68 bronze badges 2
  • 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
Add a ment  | 

3 Answers 3

Reset to default 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);

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

发布评论

评论列表(0)

  1. 暂无评论