Get the IDs of all Child elements using JavaScript

avatar

Borislav Hadzhiev

Mon Jan 03 20222 min read

banner

Photo by Alex Blăjan

Get the IDs of all Child elements using JavaScript #

To get the IDs of all child elements:

  1. Use the Array.from() method to convert the children collection to an array.
  2. Use the map() method to iterate over the array.
  3. On each iteration, return the id of each element.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="parent"> <p id="child1">Child 1</p> <p id="child2">Child 2</p> <p id="child3">Child 3</p> <p id="child4">Child 4</p> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const parent = document.getElementById('parent'); const children = Array.from(parent.children); const ids = children.map(element => { return element.id; }); console.log(ids); // 👉️ ['child1', 'child2', 'child3', 'child4']

The children property returns an HTMLCollection which contains all of the child elements of the element on which the property was accessed.

To be able to use the Array.map method we had to convert the collection to an array.

The function we passed to the map method gets called with each element (child) in the array.

The map method returns a new array that contains all of the elements we returned from the callback function.

On each iteration, we simply return the element's id.

If you need to filter elements based on specific type, e.g. only p elements, use the forEach method instead.

index.js
const parent = document.getElementById('parent'); const children = Array.from(parent.children); const ids = []; children.forEach(element => { if (element.tagName === 'P') { ids.push(element.id); } }); console.log(ids); // 👉️ ['child1', 'child2', 'child3', 'child4']

The function we passed to the Array.forEach() method gets called with each element in the array.

On each iteration, we check if the tagName property of the element is equal to P.

If the element is a paragraph, we push it to the ids array.

Note that the tagName property returns the element's tag name in upper case.

Use the search field on my Home Page to filter through my more than 1,000 articles.