Home > Software engineering >  Get the div of an array from an HTMLCollection
Get the div of an array from an HTMLCollection

Time:10-28

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  id="one">a</div>
<div  id="two">b</div>
<div  id="three">c</div>
<div  id="four">d</div>
<div  id="five">e</div>

CodePudding user response:

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  id="one">a</div>
<div  id="two">b</div>
<div  id="three">c</div>
<div  id="four">d</div>
<div  id="five">e</div>

CodePudding user response:

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  id="one">a</div>
<div  id="two">b</div>
<div  id="three">c</div>
<div  id="four">d</div>
<div  id="five">e</div>

  • Related