JavaScript Code

How to get children of div using JavaScript?

Tutorials using JS

Get children of div

given a div element in HTML document, get the children of the div using JavaScript


to get the children of div element, we can use Element.children property


where myDiv is the given div element

children property returns the children of the calling element as an HTMLCollection. HTMLCollection is an array like collection of HTML elements


in the following HTML code, we have a div element with id "myDiv" and it has three children. we use children property on the div element and get the children

<!DOCTYPE html>
<h1>JavaScript Tutorial</h1>
<h2>Get children of div</h2>
<button id="myBtn">Click me</button><br>
<div id="myDiv">
  <p>This is a paragraph.</p>
  <div>This is an inner div.</div>
  <div>This is another inner div.</div>
<pre id="output"></pre>

document.getElementById("myBtn").addEventListener("click", function() {
  const myDiv = document.getElementById("myDiv");
  //get children of the div element
  const myDivChildren = myDiv.children;
  //iterate over each of the items using loop
  for ( let i = 0; i < myDivChildren.length; i++ ) {
    document.getElementById("output").innerHTML += i + " - " + myDivChildren[i].textContent + "\n";


Copyright @2022