Question

Ok. I'm trying to get into the finer details regarding the DOM(document object module) and I seem to have situation.

Here is my HTML

<div class="parentDiv">
    <div>Child 1</div>
    <div>Child 2</div>
    <div>Child 3</div>
    <div>Child 4</div>
    <div>Child 5</div>
    <div>Child 6</div>
</div>

Simple. 6 child div's nested in a parentDiv

Now i am accesing the elemts using this Javascript

var parent = document.getElementsByClassName("parentDiv");
for (var i = 0; i < parent.length; ++i) {
  var item = parent[i]; 
  console.log(item);
}

So i run my program and I am expecting the console log to have 6 entries for my 6 div's. However i am seeing just one log entry which means that my Loop has an issue and is not reiterating.

FIDDLE

Where am I going wrong. Isn't the nodelist like an array? If yes then why doesn't my loop work?

EDIT: Check this link https://developer.mozilla.org/en-US/docs/Web/API/NodeList and scroll to the Example . It says "It's possible to loop over the items in a NodeList". How can this be done

Was it helpful?

Solution

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);

});

OTHER TIPS

You are getting all elements that contain the class name "parentDiv", which is only your one parent item. What you actually want are all the divs inside that parent.

var parents = document.getElementsByClassName("parentDiv");
for (var i = 0; i < parents.length; ++i) {
  var parent = parents[i]; 
  var children = parent.getElementsByTagName("div");
  for (var j = 0; j < children.length; ++j) {
    var item = children[i];
    console.log(item);
  }
}

To capture the node list of elements following the parentDiv, you can use:

var parentNode = document.getElementsByClassName("parentDiv")[0];

var childNodesList = parentNode.getElementsByTagName( "div" );

It will fetch you all the div elements inside the parentDiv.

hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top