JQuery: return value of each instance of the specified attribute

I am browsing a webpage and I need to return every VALUE attribute (note: not an element) of any element marked with a specific attribute.

Below is an example page. The structure and order vary from page to page, but I focus only on returning the values ​​of each instance of attrX (red, blue, green, purple, etc.).

<div attrX="red"></div> <div attrX="blue"></div> <span attrX="green></span> <div> <p attrX="purple"></p> </div> 

how can I use jQuery to return an array of values ​​for each instance on the attrX attribute page in the following format (the order doesn't really matter)?

 [0]->"red" [1]->"blue" [2]->"green" [3]->"purple" 

Thanks!

+4
source share
2 answers

Try the following:

 var values = []; $('[attrX]').each(function() { var value = $(this).attr('attrX'); values.push(value); }); 

See here for jsFiddle.

+6
source

Try the following:

 var values = $('[attrX]').map(function() { return $(this).attr('attrX'); }).get(); 
+1
source

Source: https://habr.com/ru/post/1383473/


All Articles