JavaScript Code


How to iterate over children of div using JavaScript?


Tutorials using JS

Iterate over children of div

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

Solution

to iterate over the children of the given div element, first get the children of div element using Element.children property, and use a for loop to iterate over the items of HTMLCollection that children property has returned

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 += "Child " + i + " - " + myDivChildren[i].textContent + "\n";
  }
});
</script>

</body>
</html>

Copyright @2022