-1

I'm trying to select an element with JavaScript using the following snippet of code inside an AngularJS application.

var assicurazione = document.getElementsByClassName("assicurazione");
var aLength = assicurazione.length;

for(var key in assicurazione){
   console.log("key: ", key);
   console.log("assicurazione[key] ", assicurazione[key]);
}

console.log("assicurazione element: ", assicurazione);
console.log("assicurazione.length: ", aLength);

for(var a = 0; a < aLength; a++){
   console.log("Element: ", assicurazione[a]); // not firing
   console.log("a value: ", a); // not firing
}

The output of the console.log is the following:

enter image description here

The loop is not working as expected because the length is 0, but the element has a length property and in this case it is set to 16 so I have no idea why it wouldn't loop through the element.

Anyone that can help me?

lin
  • 17,956
  • 4
  • 59
  • 83

2 Answers2

0

When I run your code in the context of this page -- but changing the classname -- it works for me as expected. I suspect something else is likely going on with your code. Have you tried angular.element?

https://docs.angularjs.org/api/ng/function/angular.element

var assicurazione = document.getElementsByClassName("module");
var aLength = assicurazione.length;

console.log(assicurazione, aLength);

for(var a = 0; a < aLength; a++){
   console.log(a);
}
Pytth
  • 4,008
  • 24
  • 29
  • Thanks for your answer, I already tried wrapping the element with angular.element, no luck tho' – 404answernotfound Apr 21 '17 at 16:47
  • Is there something else in your code changing some native prototypes? I wonder if your `Array.prototype` or `NodeList.prototype` may have been altered by some other code? Because as other's have said, the code you show works fine. This almost certainly points to something else being the problem. – Pytth Apr 21 '17 at 16:48
-1

If you wanted to access each element, your loop would need to look more like this, ignoring the changes I've made to variable names.

var elements = document.getElementsByClassName("mine");
var aLength = elements.length;

console.log(aLength);
console.log(elements);

for(var a = 0; a < aLength; a++){
   console.log(elements[a]);
}

Check out the working example on jsfiddle.

Todd Chaffee
  • 6,754
  • 32
  • 41
  • Except it does work. HTMLCollection is an array-like collection. Try the jsfiddle, or refer to the MDN docs. https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection – Todd Chaffee Apr 21 '17 at 16:55