0

Given the following markup, how can I return with jQuery all the data-foo values with the class .bar?

<ul id="foobar-list">
    <li data-foo="1">Alpha</li>
    <li data-foo="2" class="bar">Beta</li>
    <li data-foo="3" class="bar">Gamma</li>
    <li data-foo="4">Delta</li>
</ul>

Here's my progress so far:

var arr = [];
$('#foobar-list .bar').each(function() {
    var arr[] = $(this).data('foo');
});
Ryan
  • 14,682
  • 32
  • 106
  • 179

3 Answers3

3

How about using .map:

var arr = $(".bar[data-foo]").map(function() {
    return $(this).data("foo");
}).get();
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Yup i would've used map as well to convert one collection to another.. +1 – PSL Oct 03 '13 at 15:11
  • Confirmed: http://jsfiddle.net/SGMm7/ Thanks. Out of curiosity, what is the advantage of using `map` over `arr.push`? – Ryan Oct 03 '13 at 15:15
  • 1
    @Ryan -- Not sure about the actual performance gains (have to setup a jsperf for that), overall, it's more convenient. No worries about declaring an array outside the loop or pushing, simply give a selector and return the criteria! – tymeJV Oct 03 '13 at 15:17
1

The following should work:

var arr = [];
$('#foobar-list .bar').each(function() {
    arr.push($(this).data('foo'));
});
marcellscarlett
  • 388
  • 2
  • 17
0

Remove the var inside the loop - you're redeclaring the variable.

var arr = [];
$('#foobar-list .bar').each(function(index) {
    arr[index] = $(this).data('foo');
});

http://jsfiddle.net/QfSLE/

logic-unit
  • 4,195
  • 12
  • 47
  • 72