Victor Le
Victor Le

Reputation: 1788

Looping through Array is giving me 0 lengths

This should be a fairly simple process but I'm having the most difficult time with it. I had to find a set of elements. So I had to dig through an element that contain a child element which then contain another child element that has the array of items I need to do stuff with. I was able to console out the final array but have trouble getting the length of it.

This is what it looks like in the console

console.log(angular.element(element[0].children[0])[0].children);
console.log(angular.element(element[0].children[0])[0].children.length);

var myArray = angular.element(element[0].children[0])[0].children;

for(var i = 0; i < myArray.length; i++){
    console.log(i + " object found");
  }

So pretty much my for loop isn't getting anything. Obviously because the length is 0 when it should be 3. Can someone tell me if I'm going crazy or not.

UPDATE

Heres a Plunker if you guys wanna check it out. Everything is already set. Just go into the developer tool on your browser. The only difference I did was added a few extra elements. So instead of 3 I made 5. And I also added a couple of more methods. Specifically targeting an ID. But still no luck implementing it into a for loop.

Upvotes: 1

Views: 110

Answers (1)

PinkTurtle
PinkTurtle

Reputation: 7041

Logging element[0].innerHTML gives :

<div class="ng-binding" ng-bind-html="renderHtml(content)"></div>

Your div is empty (doesn't have #mynewid and children) because at the time you are requesting them, the elements are not yet created by the renderHtml(content) function.

Example:

setTimeout(function() {
    var myArray = document.getElementById("mynewid").children;
    for(var i = 0; i < myArray.length; i++){
        console.log(myArray[i] + " object found");
    }
}, 1000);

Upvotes: 1

Related Questions