Tips for filling an array with a div ID based on the div's class name

Imagine I have 4 divs with the same class but unique ID's like this;

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

Now, if I create an array in the script as shown below;

var pressArray =[]

How can I populate this array with the ID names of all elements with the class name "press" in the HTML body?

Answer №1

To retrieve an array of id's, you can utilize the map() and get() methods.

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

Answer №2

You can achieve the same result without using jQuery like this:

pressArray = [];
[].slice.call(document.querySelectorAll('.press')).forEach(function(el) {
  pressArray.push(el.id)
});
document.write(pressArray);
<div id="Komori1" class="press"></div>
<div id="Komori2" class="press"></div>
<div id="PressD" class="press"></div>
<div id="PressE" class="press"></div>

Answer №3

To make it simple, select all elements with the class ".press" and then extract their id values into an array.

Without using jQuery:

var pressElements = document.querySelectorAll('.press');
var pressIds = [].map.call(pressElements, function(element) {
  return element.id;
});

alert(pressIds);
<div id="Komori1" class="press">
<div id="Komori2" class="press">
<div id="PressD" class="press">
<div id="PressE" class="press">

Using jQuery:

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

alert(pressIds);
<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">

Answer №4

let pressList = [];

$(".press").each(function() {
  pressList.push($(this).attr('id'));
});

$(".result").html(pressList.toString());
<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">

  
<div class="result"></div>

Answer №5

Parse through all elements containing the press class and store their id values in the pressArray variable.

var pressArray = [];
$(".press").each(function(i) {
  pressArray.push(this.id);
});
alert(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">

You can implement a for loop using pure JavaScript to iterate over elements with the press class.

var pressArray = [];
for(var i=0, n=document.getElementsByClassName("press"); i<n.length; i++) {
  pressArray.push(n[i].id);
};
alert(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">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Svelte's glitchy flip animation

My Svelte application includes a list with items that feature a built-in flip animation when they are moved. Each item also contains an absolutely positioned menu with a z-index of 10. However, when the flip animation is triggered, the menu falls behind th ...

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...

The argument type of '() => JQuery' cannot be assigned to a parameter type of '() => boolean'

Having trouble writing a jasmine test case for my method due to an error: spec.ts(163,18): error TS2345: Argument of type '() => JQuery' is not assignable to parameter of type '() => boolean' Any suggestions on how to resolve ...

What is the best way to implement conditional styling in Vue.js?

Looking to incorporate a conditional style into my Component. Here is my component: <site-pricing color="primary" currency="$" price="25" to="/purchase" > <template v-slot:title>Complete</templat ...

Easily choose multiple items at once by searching with react-select

I have implemented react-select to showcase a searchable drop-down list of items where users can select multiple items. The list is lengthy, and users often find it tedious to multi-select many items that match the same filter string. This is because each ...

Tips for keeping a label above an input field

Is it possible to add a styled label on top of an input element? I have seen images placed inside input elements for indicating the type of input accepted. For example, in a login form, a user icon represents the username field and a key icon represents th ...

What is the best method for converting a string to an integer when transitioning from CSV to JSON format?

Upon discovering this code snippet designed to convert a CSV file into JSON format, I encountered a specific requirement. In this scenario, the credit field needs to be an integer, which means it should not be enclosed within quotation marks like "". I de ...

Tips for leveraging OOP to eliminate redundant code repetition

How can I avoid repeating code when displaying multiple quizzes on the same page? Currently, I have a JavaScript function that duplicates everything for each quiz, with only a few variables changing in the second function. The problem arises when I need t ...

Having trouble retrieving JSON data from an AJAX request and showing it in an HTML page

Having some trouble with utilizing the New York Times bestseller list API to showcase the current top 20 in html. I've successfully retrieved the data using ajax (confirmed through developer tools) but hit a roadblock when attempting to display it on ...

What is the best way to retrieve all cell values from a Jquery Datatable?

Currently working on a school project and using jquery datatable for attendance tracking. Check out the image below: jquery datatable records https://i.sstatic.net/55AFI.jpg The goal is to gather all values from cells (with t ...

The longevity of JQuery features

As I work on setting up an on-click callback for an HTML element to make another node visible, I encountered a surprising realization. The following two statements appeared to be equivalent at first glance: $("#title").click($("#content").toggle); $("#tit ...

Mysterious python eccentricity requiring clarification

I am intrigued by a peculiar behavior in Python that I am trying to comprehend. While it doesn't seem like a bug, the reason behind this behavior eludes me. My goal is to load a group of images into a list and then manipulate them. Let's take a ...

The difference between see-through shades and rgba(0,0,0,0)

What are the primary benefits of using: background-color: rgba(0,0,0,0); over: background-color: transparent; ? ...

Sorting the table: the parser for the table.config[c] is not defined

I've been struggling with the tablesorter plugin, as it doesn't seem to be functioning properly in sorting the table. Can someone please assist me? I've been trying to solve this issue for two days now. Here is the error: table.config.pars ...

Guide on hosting two html pages on a NodeJS server

Currently, I am in the process of learning NodeJS and Javascript with a goal to construct a basic server that can host 2 HTML pages. One page should be accessible via localhost:3000/index, while the other can be reached through localhost:3000/about. While ...

The functionality of my Javascript code is restricted to a single element within a Python embedded for loop in Django2

My Python for loop is iterating through these HTML template cards, each accompanied by JavaScript. However, I'm encountering an issue where the JavaScript only seems to work on the first element (specifically, it's meant to retrieve the seeked po ...

Leveraging the power of image-based input with the dynamic trio of AJAX, JQuery

I've been working on a rock, paper, scissors game using AJAX to learn JQuery, and I believe it's almost complete. However, I'm facing an issue with getting my buttons to function properly. My approach involves using <input type="image" .. ...

jQuery toggle buttons to show or hide on radio button selection

I have a pair of buttons and a pair of radio buttons Buttons 1) btnErp 2) btngoogle Radio Buttons 1) rdiogoogle 2) rdioErp When I select 'rdiogoogle', 'btngoogle' should be visible while 'btnErp' should be hidden. Conve ...

In Angular and Sublime Text 2, I'm having an issue where one file is working perfectly while the other one isn't. I've closely examined both

As I follow along with the angularjs tutorial, I am attempting to replicate each step. In the section on routes, we are instructed to create a file called app.js. I am using SublimeText2 as my text editor, with both syntax settings set to javascript. Surpr ...

Arranging elements in a list according to their position on the canvas using AngularJS

I am currently working on drawing rectangles on an html5 canvas using the JSON format provided below. My goal is to sort the array based on the x and y locations of each element. { "obj0": { "outerRects": [ { "outerRectRoi": { "x1": 0, " ...