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

Solution

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

myDiv.children

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

Program

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>
<html>
<body>
<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>
</div>
<pre id="output"></pre>

<script>
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";
  }
});
</script>

</body>
</html>

Copyright @2022