Julien S
Julien S

Reputation: 91

Implement an array using foreach in Javascript

I've a several li elements which have as class : multiselect_selected_profil.

<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="60">
    <span class="multiselect_profil">C1</span>
</li>

I would like that for each li that has this specific class, I get its data-id and then put it into an array. At then end of the process I would like to have an array which contains all the ids.

Here is what I've tried :

$(".multiselect_selected_profil").each(function(){
    var iObjetId = $(this).attr('data-id');
    // ???
}

Upvotes: 1

Views: 101

Answers (5)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

The fastest way would be specifying the data-id right in the selector description and use toArray() function to retrieve all the elements contained in the jQuery set, as an array:

var arr = $(".multiselect_selected_profil[data-id]").toArray();

Upvotes: 0

Karan Adhikari
Karan Adhikari

Reputation: 485

var ids = [];

$(".multiselect_selected_profil").each(function(){
   if($(this)..hasClass( "specific_class_name" )){
     ids.push($(this).attr('data-id'));
   }
});

now you will get all ids those contains specific class

Upvotes: 0

DiniZx
DiniZx

Reputation: 126

Have a look attached snippet.

var dataid = [];  //Initialize the array variable


$(".multiselect_selected_profil").each(function(){
    var iObjetId = $(this).attr('data-id');
    dataid.push(iObjetId);    
});

alert(dataid);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="60"><span class="multiselect_profil">C1</span></li>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="61"><span class="multiselect_profil">C2</span></li>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="62"><span class="multiselect_profil">C3</span></li>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="63"><span class="multiselect_profil">C4</span></li>
<li id="li60" class="multiselect_my_profil multiselect_selected_profil" data-id="64"><span class="multiselect_profil">C5</span></li>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337627

You can use map() to create an array from a set of matched elements:

var arr = $(".multiselect_selected_profil").map(function() {
    return $(this).data('id');
}).get()

Upvotes: 2

Roxoradev
Roxoradev

Reputation: 893

var ids = []
$(".multiselect_selected_profil").each(function(){
var iObjetId = $(this).attr('data-id');
ids.push(iObjetId);
}

Create an empty array and push ids

Upvotes: 2

Related Questions