I have a list of jquery elements with a data attribute.
Now I want to get a list of these data attributes.
As the data
-attribute is some kind of an object property, I thought this might work with underscores pluck
method.
Is this even possible?
See this short example:
var divs = $("div");
// now do something
// expected result: [1, 2, 3]
<script src="https://cdnjs.com/libraries/underscore.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-foo="1">a</div>
<div data-foo="2">b</div>
<div data-foo="3">c</div>
<div>x</div>
Solution
Based on @romeo-sierra this is the way I wrote it down (as I already have jquery objects). Underscores pluck is superfluous
var foos = $("div").map(function() {
return $(this).data("foo");
}).toArray();
console.log(foos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-foo="1">a</div>
<div data-foo="2">b</div>
<div data-foo="3">c</div>
<div>x</div>
Vanilla JS can accomplish this just fine, no jQuery nor any other library needed:
const foos = [...document.querySelectorAll('[data-foo]')]
.map(elm => elm.dataset.foo);
console.log(foos);
<div data-foo="1">a</div>
<div data-foo="2">b</div>
<div data-foo="3">c</div>
<div>x</div>
ES5 version:
var foos = Array.prototype.map.call(document.querySelectorAll('[data-foo]'), function(elm) {
return elm.dataset.foo;
});
console.log(foos);
<div data-foo="1">a</div>
<div data-foo="2">b</div>
<div data-foo="3">c</div>
<div>x</div>
How about the following, that uses pure jQuery? (since you already are using it)
var arr = [];
$('div[data-foo]').each(function(){
arr.push($(this).data("foo")); // should return the value
});
console.log(arr);
Check this fiddle out.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With