javascript

Get all child elements of parent element in javascript

var parent = document.getElementById("parent_id");
var childrens = parent.children;
//RETURNS ALL CHILD ELEMENTS HTMLCollection ARRAY

If you want to get all child elements of a parent element in javascript you can use 'children' property. It will return the HTMLCollection array of all elements.

Example

For example, if there is a div element which has id 'master' and it has child elements like paragraphs 'p' and headings 'h2' and you want to get the collection of these elements you can use below code

 Success is a journey not destination 
 If you want to be successful you have to enjoy every step that you are taking to achieve your goals and dreams. 
There is no shortcut to success. You will have to work hard continuously to make your dreams come true.

To get all child elements of master id element you can use below javascript code.

document.getElementById("master").children

Live Demo

<ul>
	<li>First Element</li>
	<li>Second Element</li>
	<li>Third Element</li>
	<li>Fourth Element</li>
</ul>

<script>
	var ul_elements = document.getElementsByTagName("ul")[0];
	li_childrens = ul_elements.children; // Get all childrens here

    //Loop through childrens
    for (var i=0; i < li_childrens.length; i++) {
        if (i%2 ==0) {
            //Change children color to red
            li_childrens[i].style.color = "red"; 
        } else {
            //change children color to green
            li_childrens[i].style.color = "green";
        }
    }
</script>
We have four li HTML elements here which are enclosed inside a ul element. We are getting parent ul element using 'getElementsByTagName' and getting its children using parent.children syntax.
We are also iterating over child elements and assigning colors based on different conditions. The code demo of this code snippet can be found above.
Was this helpful?