-1

Alright guys, I'm having the error

Uncaught TypeError: Cannot read property 'left' of undefined

When using this code

var y=document.getElementsByClassName('snake-snakebody-block          snake-snakebody-alive  snake-snakebody-alive')
//console.log(y.style)
console.log(y.style.left)
console.log(y.style.top)

on this element

<div class="snake-snakebody-block          snake-snakebody-alive  snake-snakebody-alive" style="left: 40px; top: 580px; width: 20px; height: 20px; z-index: 5;"></div>

And I'm at a loss. how can I fix

cacti5
  • 2,006
  • 2
  • 25
  • 33
Giga Bowser
  • 11
  • 1
  • 1
  • What's the reason for assigning the class `snake-snakebody-alive` twice to the same element? – faintsignal May 18 '18 at 00:02
  • https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName – faintsignal May 18 '18 at 00:03
  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – faintsignal May 18 '18 at 00:07

1 Answers1

0

Because getElementsByClassName returns a list of elements you have to take the first element from array like this:

console.log(y[0].style.left)

AnilRedshift
  • 7,937
  • 7
  • 35
  • 59