Julien S Julien S - 5 months ago 9
jQuery Question

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');
// ???
}

Answer

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>