Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab values of an attribute from all elements in jQuery

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.

like image 255
Joshua Burns Avatar asked May 08 '20 20:05

Joshua Burns


People also ask

What is the use of attr () method in jQuery?

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.

How get data attribute value of class in jQuery?

$('. 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 .

What is attr and prop in jQuery?

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 .


Video Answer


3 Answers

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');
});
like image 109
Xth Avatar answered Sep 30 '22 05:09

Xth


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>
like image 21
Uyghur Lives Matter Avatar answered Sep 30 '22 05:09

Uyghur Lives Matter


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>
like image 43
terrymorse Avatar answered Sep 30 '22 06:09

terrymorse