How to get a list of identifiers in a specific class using jquery?

eg.

<div class="myclass" id="div_1"></div> <div class="myclass" id="div_2"></div> <div class="notmyclass" id="div_3"></div> 

I would like the resulting array to be similar ["div_1", "div_2"]

+6
source share
3 answers

After selecting $(".myclass") you can use the .map() [ docs ] method to take the .id each element. This will return a jQuery array object containing identifiers.

 var ids = $(".myclass").map(function() { return this.id; }); 

Add .toArray() [ docs ] to the end if you need a real array.

+11
source
 var IDs = []; $('.myclass').each(function(){ IDs.push( this.id ); }); 
0
source

Other than .map you need .get() if you want to get the array at the end:

 $('.myclass').map(function() { return this.id; }).get(); 
0
source

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


All Articles