Aceman
Aceman

Reputation: 37

Issue with document.getElementsByClassName

I am using it to show an item that needs to stay hidden until I click on a button to display it, the thing is that it does what It's meant to be doing but still shows an error on the console. Here is the code that I am using.

    <button onclick="MostrarPuntaje()">Mostrar Puntajes</button>

and the Javascript function that is called by the button:

    function MostrarPuntaje(){

var elements = document.getElementsByClassName('puntaje');
for(var i = 0; i!=elements.lenght; i++){
    elements[i].style.visibility = 'visible';
}

Finally, this is the error the console is showing, even tho it really displays the items that were hidden.

tablero.html:53 Uncaught TypeError: Cannot read property 'style' of undefined

The line 53 is the following (It is inside the for loop):

elements[i].style.visibility = 'visible';

I hope you could understand my code and my words since I can't seem to find a proper way to explain this mistake, I honestly don't know what I'm doing wrong, thanks for reading and I hope you can help me.

Upvotes: 1

Views: 88

Answers (1)

JPS
JPS

Reputation: 2760

It's because of typo. Inside for loop change the condition to elements.length instead of elements.lenght.

Why it works

The for loop condition, i!=elements.lenght will be interpreted as i!= undefined and the condition is always true since the index starts from 0 and increases on.

So elements[0] works well. And then it'll move to the next step elements[1] which is undefined and it throws error since we are accessing the style property of undefined

Upvotes: 2

Related Questions