children property of You can use theproperty of getElementById() method in JavaScript to get or extract unique ids of all the DIV elements inside a DIV element. The name of the property itself says it all. I am sharing a simple example here, which shows how to get the IDs of every child DIV element using the children property.

Using children Property to get all Child DIV IDs

<!DOCTYPE html> <html> <head> <title>Get all child DIV ids inside a DIV using JavaScript</title> </head> <body> <p>Using children property in JavaScript to get all the child DIV IDs!</p> <div id="birds" style="border:solid 1px #CCCC;padding:10px;"> <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> function findElementID() { var birds = document. getElementById ('birds'). children ; var msg = document. getElementById ('msg'); for (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 get all DIV element IDs on web page, parent or child, in JavaScript. In this case, use the getElementByTagName() method.

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

<!DOCTYPE html> <html> <head> <title>Get all DIV IDs using JavaScript</title> </head> <body> <p>Using getElementsByTagName() in JavaScript to IDs of every DIV element!</p> <div id="birds"> <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> function findElements() { var ele = document. getElementsByTagName ('div'); var msg = document. getElementById ('msg'); for (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 any element on a web page. Just make sure, all the IDs are unique and that’s how it should be.

Thanks for reading. ☺

← PreviousNext →