Categories
JavaScript Answers

How to loop over the child divs of a div and get the ids of the child divs with JavaScript?

Spread the love

Sometimes, we want to loop over the child divs of a div and get the ids of the child divs with JavaScript.

In this article, we’ll look at how to loop over the child divs of a div and get the ids of the child divs with JavaScript.

How to loop over the child divs of a div and get the ids of the child divs with JavaScript?

To loop over the child divs of a div and get the ids of the child divs with JavaScript, we can use some DOM methods and the spread operator.

For instance, we write:

<div id="test">
  <div id="test-1"></div>
  <div id="test-2"></div>
  <div id="test-3"></div>
  <div id="test-4"></div>
</div>

to add a div with divs.

Then we write:

const childDivs = document.getElementById('test').getElementsByTagName('div');
const ids = [...childDivs].map(d => d.id)
console.log(ids)

to select all the child divs in the div with ID test with document.getElementById('test').getElementsByTagName('div').

Then we spread the returned node list into an array and call map with a callback to return the id attribute value from each div.

Therefore, ids is ["test-1", "test-2", "test-3", "test-4"].

Conclusion

To loop over the child divs of a div and get the ids of the child divs with JavaScript, we can use some DOM methods and the spread operator.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *