C Dub
C Dub

Reputation: 41

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.

Upvotes: 3

Views: 184

Answers (3)

John Mack
John Mack

Reputation: 73

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>

Upvotes: 3

Htet Oo Wai Yan
Htet Oo Wai Yan

Reputation: 133

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);

Upvotes: 1

Phil
Phil

Reputation: 164729

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>

Upvotes: 1

Related Questions