Flav Flavius Flav Flavius - 10 months ago 68
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 class="tbh lista">
<a href="#"><img src="images/mail.png"></a>
<li class="lista">
<a href="#" onclick="changeClass()" id="phone"><img src="images/phone.png"></a>
<li class="lista hidden">

This is the script:

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


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 Source

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

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


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