How to retrieve IDs of Child DIV elements within a Parent DIV using JavaScript

← PrevNext →

Last updated: 5th January 2025

You can use the children property of the getElementById() method in JavaScript to retrieve the unique IDs of all DIV elements within a parent DIV. This property returns an HTMLCollection of the child elements. Below is a simple example demonstrating how to get the IDs of each child DIV element using the children property.

Using children Property to get all Child DIV IDs

<!DOCTYPE html>
<html>
<body>
    <h1>Using children property in JavaScript to get all the child DIV IDs!</h1>

    <!--The parent DIV-->
    <div id="birds">
        <!--The child DIVs-->
        <div id='be'>Bald Eagle</div>
        <div id='mv'>Mourning Dove</div>
        <div id='ct'>Canyon Towhee</div>
    </div>
  
    <p><input type='button' value='Click it' onclick='findElementID()' /></p>
    <p id="msg"></p>
</body>
<script>
  let findElementID = () => {
    const birds = document.getElementById('birds').children;
    
    let msg = document.getElementById('msg');
    msg.innerHTML = '';

    // Loop through all the child elements inside the parent DIV.
    for (let i = 0; i <= birds.length - 1; i++) {
      msg.innerHTML = msg.innerHTML + '<br />' + birds[i].id;
    }
  }
</script>
</html>
Try it

The property children, returns an HTMLCollection object.

The elements are the immediate child elements (or children) of the parent element (a DIV element in our example). If you see the length of the variable birds (in the above example), it would return 3, which indicates, there are 3 elements present inside the parent element.

console.log(birds.length);

Get IDs of all DIV elements

You can also retrieve the IDs of all DIV elements on a web page, whether they are parent or child elements, using JavaScript. To do this, use the getElementsByTagName() method.

The getElementByTagName() takes a parameter in the form of the tagname. Here, the tagname would be "DIV".

<!DOCTYPE html>
<html>
<body>
    <h1>Using getElementsByTagName() in JavaScript to IDs of every DIV element!</h1>

    <!--The parent DIV-->
    <div id="birds">
        <!--The child DIVs-->
        <div id='be'>Bald Eagle</div>
        <div id='mv'>Mourning Dove</div>
        <div id='ct'>Canyon Towhee</div>
    </div>
  
    <p><input type='button' value='Click it' onclick='findElements()' /></p>
    <p id="msg"></p>
</body>
<script>
    let findElements = () => {
        const ele = document.getElementsByTagName('div');

        let msg = document.getElementById('msg');
        msg.innerHTML = '';

        // Iterate the "ele" object and get the ids of all elements of type DIV.
        for (let i = 0; i <= ele.length - 1; i++) {
            msg.innerHTML = msg.innerHTML + '<br />' + ele[i].id;
        }
    }
</script>
</html>
Try it

You can use the above methods to get the ID of any element on a web page. Just ensure that all IDs are unique, as they should be.

← PreviousNext →