Ahmed Siddiqui Ahmed Siddiqui - 4 months ago 6
CSS Question

How to populate array with a div ID by the divs class name

Lets say I have 4 divs that share the same class and unique ID's like the following;

<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">


And I create an array in the script like the following;

var pressArray =[]


Now I want to populate this array with the Id names of all instances of class name "press" in the html body, how I can do this is?

Answer

You can use map() and get() methods to get array of id's

var pressArray = $('.press').map(function() {
  return this.id;
}).get();

console.log(pressArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">