Flav Flavius Flav Flavius - 1 month ago 14
HTML Question

Javascript only works partially

I want to create a script that will remove a class on two li items after click and add a class to another li item. I have used the .className method but it only works partially.

<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li class="tbh lista">
<a href="#"><img src="images/facebook.png"></a>
</li>
<li class="tbh lista">
<a href="#"><img src="images/mail.png"></a>
</li>
<li class="lista">
<a href="#" onclick="changeClass()" id="phone"><img src="images/phone.png"></a>
</li>
<li class="lista hidden">
<p>text</p>
</li>
</ul>
</div>


This is the script:

function changeClass(){
var elements = document.getElementsByClassName('tbh');
for (var i = 0, len = elements.length; i <=len; i++) {
elements[i].className='hidden';

console.log('aaa');
}
}


After I click the li item once, only one of the li items disappears and I get an error. I have to click it twice for it to function properly. I can t find the error.
These are displayed in console.log: aaa
Uncaught TypeError: Cannot set property 'className' of undefined

Answer

This is because document.getElementsByClassName returns HTMLCollection but not Array. So change your string

var elements = document.getElementsByClassName('tbh');

to

var elements = Array.from(document.getElementsByClassName('tbh'));