1

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

5 Answers 5

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

Create an empty array and push ids

Sign up to request clarification or add additional context in comments.

Comments

2

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()

Comments

1

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>

1 Comment

What if that class is being added to the element after page load? I'm assuming it will be based on it's naming
0
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

Comments

0

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.