0

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".)

JM Taylor
  • 3
  • 3
  • 1
    Possible duplicate of [jQuery get id of element by searching for it by class](http://stackoverflow.com/questions/5841650/jquery-get-id-of-element-by-searching-for-it-by-class) – Cyril Iselin May 18 '16 at 17:09

2 Answers2

3

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">
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • Thank you for your answer! This also gave me exactly the array I wanted. Actually, I don't totally understand the logic (started learning web dev a few months ago), but it works and I'm reading the jQuery documentation now to figure it out. Thanks again! – JM Taylor May 18 '16 at 18:19
1

You could use:

var ary = [];
$('.viewButton').each(function(){ ary.push(this.id) })
j08691
  • 204,283
  • 31
  • 260
  • 272
  • Thank you! This was great. The resulting array was exactly what I needed. I'm still learning, and this was a really good function learn! – JM Taylor May 18 '16 at 18:10