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
  • 2
  • 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
  • 30,714
  • 6
  • 20
  • 43
  • Um, actually, it's [not too good to use `for..in` even with spead here](https://stackoverflow.com/questions/500504/why-is-using-for-in-for-array-iteration-a-bad-idea); instead of the spread, you could just do `for..of` (it also works on Iterables) – FZs Jul 23 '21 at 17:01
  • Console log Show null – Agnes Jul 23 '21 at 18:17