Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

125
Views
Create an array from 'for of' loop outputs

I have a for of statement in JS that returns HTML element ids but they are in multiple outputs. I would like to take these outputs and put them in an array.

For example the HTML is:

<div>
    <button id="savebtn-1"></button>
</div>
<div>
    <button id="savebtn-2"></button>
</div>

and my JS is:

const elements = document.querySelectorAll("button");
for (const element of elements) {
    let id = elements.getAttribute("id");
}

console.log(id) will show:

savebtn-1

savebtn-2

How can I get these outputs into an array?

Thanks for any attention you may give this question.

almost 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Make another array and store all the id's inside that array.

const resultArray = [];
const elements = document.querySelectorAll("button");

for (const element of elements) {
    const id = element.getAttribute("id");
    resultArray.push(id);
}
console.log(resultArray);
<div>
<button id = "savebtn-1">Button 1</button>
</div>
<div>
<button id = "savebtn-2">Button 2</button>
</div>

almost 4 years ago · Santiago Trujillo Report

0

Use Array.from() on the NodeList and a custom mapper to extract the IDs

const idArray = Array.from(
  document.querySelectorAll("button"),
  ({ id }) => id
);

console.log(idArray);
<div>
  <button id="savebtn-1">Button #1</button>
</div>
<div>
  <button id="savebtn-2">Button #2</button>
</div>

almost 4 years ago · Santiago Trujillo Report

0

You can create an empty array and push ids into that array.

const elements = document.querySelectorAll("button");

const idArray = [];

for (const element of elements) {
    let id = elements.getAttribute("id");
    idArray.push(id);
}

console.log('idArray ', idArray);
almost 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!