Reputation: 3
I have 4 html input elements:
<input type="checkbox" class="viewButton" id="html-button">
<input type="checkbox" class="viewButton" id="css-button">
<input type="checkbox" class="viewButton" id="javascript-button">
<input type="checkbox" class="viewButton" id="output-button">
What I'd like to do is get the name of each id in every element with a class of "viewButton" and put them in an array.
In order to do that, I wrote this:
var viewButtonsArray = [];
viewButtonsArray.push($(".viewButton"));
var buttonIdsArray = [];
for (var i = 0; i < viewButtonsArray[0].length; i++) {
buttonIdsArray.push(viewButtonsArray[0][i].id);
}
The code works. However, I was wondering if there was an easier way to do this.
Thanks!
(I don't think this is a duplicate. The link being claimed as a duplicate solves a problem regarding an element within another element, the parent has the class, child has the id. My question is about elements with BOTH a class and id, hence the title "ids of every element with a certain class" and not "id of elements within a parent element with a class".)
Upvotes: 0
Views: 62
Reputation: 122077
You can do this with map()
and get()
DEMO
var viewButtonsArray = $('.viewButton').map(function() {
return $(this).attr('id');
}).get();
console.log(viewButtonsArray)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="viewButton" id="html-button">
<input type="checkbox" class="viewButton" id="css-button">
<input type="checkbox" class="viewButton" id="javascript-button">
<input type="checkbox" class="viewButton" id="output-button">
Upvotes: 3
Reputation: 207923
You could use:
var ary = [];
$('.viewButton').each(function(){ ary.push(this.id) })
Upvotes: 1