2

I would like to return only the id of each div and keep them in an array :

const projects = [...document.getElementsByClassName("nav-project")];
console.log(projects);
      
//expected output : [one, two, three, four, five]
<div class="nav-project" id="one">a</div>
<div class="nav-project" id="two">b</div>
<div class="nav-project" id="three">c</div>
<div class="nav-project" id="four">d</div>
<div class="nav-project" id="five">e</div>
aloisdg
  • 22,270
  • 6
  • 85
  • 105
Aurore
  • 696
  • 4
  • 16
  • 1
    Does this answer your question? [Get the ID's of all the elements in the array](https://stackoverflow.com/questions/40060497/get-the-ids-of-all-the-elements-in-the-array) – Heretic Monkey Oct 27 '22 at 21:06

2 Answers2

3

Try map:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

const projects = [...document.getElementsByClassName("nav-project")]
  .map(div => div.id);

  console.log(projects);
<div class="nav-project" id="one">a</div>
<div class="nav-project" id="two">b</div>
<div class="nav-project" id="three">c</div>
<div class="nav-project" id="four">d</div>
<div class="nav-project" id="five">e</div>
aloisdg
  • 22,270
  • 6
  • 85
  • 105
2

I would use Array.from() to convert a NodeList to an array of ids:

const projects = Array.from(
  document.querySelectorAll('.nav-project'),
  el => el.id
)

console.log(projects)
<div class="nav-project" id="one">a</div>
<div class="nav-project" id="two">b</div>
<div class="nav-project" id="three">c</div>
<div class="nav-project" id="four">d</div>
<div class="nav-project" id="five">e</div>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • This answer is really good because it has the additional benefit of avoiding [downleveling error](https://stackoverflow.com/a/69046124/1248177) – aloisdg Oct 27 '22 at 21:10