Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine $ and _ to pluck by data values?

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>
like image 482
ppasler Avatar asked Dec 18 '22 23:12

ppasler


2 Answers

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>
like image 133
CertainPerformance Avatar answered Jan 03 '23 03:01

CertainPerformance


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.

like image 44
Romeo Sierra Avatar answered Jan 03 '23 05:01

Romeo Sierra