JM Taylor JM Taylor - 1 year ago 55
Javascript Question

Is there a JS/jQuery function that takes the ids of every element with a certain class?

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 = [];

var buttonIdsArray = [];
for (var i = 0; i < viewButtonsArray[0].length; i++) {

The code works. However, I was wondering if there was an easier way to do this.


Answer Source

You could use:

var ary = [];
$('.viewButton').each(function(){ ary.push( })