0

I know there is many similar questions but I don't know why it doesn't work to me

I have collection

cars = document.gelementsByClassName('car');
for (i in cars){
               let attr = cars[i].getAttribute('segment');
               } 

And its going down with messege "getAttribute is not a function" and loop is not go to end. I tried use try-catch but it doesn't word loop still not go to end Even it is really error i would like to ignore this error and go to end.

Agnes
  • 77
  • 1
  • 10

1 Answers1

0

You should be using document.getElementsByClassName('car') instead.

Also, to iterate through the NodeList using a for..in loop, you have to use spread syntax (...).

var cars = [...document.getElementsByClassName('car')];
for (i in cars) {
  let attr = cars[i].getAttribute('segment');
  console.log(attr);
}
<div class="car" segment="1"></div>
<div class="car" segment="2"></div>
<div class="car" segment="3"></div>
Spectric
  • 27,594
  • 6
  • 14
  • 39