Suppose we have the following HTML:
<entries>
<entry id="1" />
<entry id="2" />
<entry id="3" />
<entry id="4" />
</entries>
Does jQuery have a built-in mechanism for retrieving all values of a specific attribute? And if not, then what is the most efficient way to retrieve them?
Eg, something similar to: $('entry').attrs('id')
, returning a list of values across all elements which returns something similar to ["1", "2", "3", "4"]
?
jQuery documentation under General Attributes (which is where attr
is found,) doesn't give any hint to such a thing existing, and I've found nothing on StackOverflow or any other support forum asking this question.
jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.
$('. myclass') will select all the elements having the class myclass , but when used . data() on it will return the data-attribute value of the first element in the matched set, thus returning 2 .
As of jQuery 1.6, the . prop() method provides a way to explicitly retrieve property values, while . attr() retrieves attributes. example. For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .
You can use something like that: https://jsfiddle.net/g903dyp6/
<entries>
<entry id="1" />
<entry id="2" />
<entry id="3" />
<entry id="4" />
</entries>
let arr = $.map($('entry'), function(el) {
return $(el).attr('id');
});
There is not a direct function to do that. However, it can be easily accomplished using .map(). E.g.,
let ids = $('entry').map(function() {
return this.getAttribute('id');
}).get();
let ids = $('entry').map(function() {
return this.getAttribute('id');
}).get();
console.log(ids);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<entries>
<entry id="1" />
<entry id="2" />
<entry id="3" />
<entry id="4" />
</entries>
Here's one way that uses the JavaScript Array .map() function:
let ids = jQuery.makeArray($('entry')).map(entry => entry.id);
console.log('ids:', ids);
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<entries>
<entry id="1" />
<entry id="2" />
<entry id="3" />
<entry id="4" />
</entries>
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