There is only one <div>
with the class parentDiv
.
Change your HTML:
<div class="parentDiv">
<div class="childDiv">Child 1</div>
<div class="childDiv">Child 2</div>
<div class="childDiv">Child 3</div>
<div class="childDiv">Child 4</div>
<div class="childDiv">Child 5</div>
<div class="childDiv">Child 6</div>
</div>
And your JavaScript:
var parent = document.getElementsByClassName("childDiv");
for (var i = 0; i < parent.length; ++i) {
var item = parent[i];
console.log(item);
}
Be wary that getElementsByClassName
is not supported in some older browsers.
Edit:
The NodeList
that you're trying to iterate over only has one element within it. Hence you only get one result. Either dig deeper into the DOM from within your loop, or leverage the use of class names for your child DOM Elements.
I presume there is a specific reason you're not using jQuery? Because it would be as simple as:
$('.parentDiv').children().each(function(){
console.log(this);
});