简体   繁体   中英

How do you get every value for an attribute that all the elements contain from a selector?

this is my first question and i hope it makes sense because i am quite a rookie at javascript/jquery.

So, i have a varying amount of elements with the custom attribute data-value=<?php echo $value ?>

Once the page has loaded I have some javascript $('[data-value]') to select all the elements on the page with the attribute 'data-value'. This returns an array with all the relevant elements. Then i tried getting the values with $('[data-value]').data('value') . Now, while this is returning the right result, it's only returning it for the first element it comes across. I tried iterating through the code with $('[data-value]')[num].data('value') where 'num' is between zero and the array length. This, sadly, didn't work.

So is there any way to grab all the values of a particular attribute that all the selected elements have?

To get the values of all the selected elements, you need to loop through the list and pick the value of those, like this:

var values = $("[data-value]").map(function(i, el) {
  return el.data('value');
});

console.log(values);

Hope that helps!

you can do something like this:

$('[data-value]').each(function(){
   console.log($(this).data('value'));
});

You can use the .each() method to iterate through your elements.

$('[data-value]').each(function() {
    console.log( $(this).data('value');
}

You can also use the for loop as you have tried, with a simple modification. When you do $('[data-value]')[num] , you actually get the native element, and not a jQuery object, so .data() is no longer available. To fix this, you can re-wrap the element in a jQuery object. $( $('[data-value]')[num] ).data('value')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM