Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the div of an array from an HTMLCollection

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>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading