Reputation: 5585
I've got buttons with a common class (buttons
). How can I add their ID
s in to an array in a reverse order?
var yourArray = [];
$('.buttons').each(function() {
yourArray.push( $(this).prop('id') );
});
Upvotes: 2
Views: 96
Reputation: 115222
You can do something simple with map()
and reverse()
var yourArray = $('.buttons').map(function() {
return this.id; // get the id
})
.get() // get the array
.reverse(); // reverse the array
console.log(yourArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="a" class="buttons"></button>
<button id="b" class="buttons"></button>
Upvotes: 2
Reputation: 337570
You could create the array by adding each element to the beginning of the array using unshift()
:
var yourArray = [];
$('.buttons').each(function() {
yourArray.unshift(this.id);
});
Alternatively you can create it in the current order and then reverse()
it. Also note that you can use map()
to create the array initially:
var yourArray = $('.buttons').map(function() {
return this.id;
}).get().reverse();
Finally you can use this.id
instead of creating a jQuery object just to access a property already accessible without the need of object creation.
Upvotes: 4