Skip to content Skip to sidebar Skip to footer

Javascript Changes One Some Class Names

my javascript function is only changing two of 4 classes. If I click it again it changes the third one but then completely ignores the last one. function move(obj,obj2) { var

Solution 1:

The method document.getElementsByClassName() returns a NodeList, which is a "live" object. That is, as the DOM changes, the NodeList instance changes with it. So, each time you change the class of one of the elements in your node list, that element is then removed from the node list because it no longer matches the class. You can use a while loop instead:

var _elements = document.getElementsByClassName(obj);
while (_elements.length) {
    _elements[0].className ='none';
}

The second problem is that you are assigning a property named className to a NodeList object. This will not affect any of the elements in that NodeList object. You need to set the className of the elements in the NodeList.

document.getElementsByClassName(obj2)[0].className = 'none';

Solution 2:

The .getElementsByClassName() method is supposed to return a NodeList (though according to MDN most browsers return an HTMLCollection), which means you need to access it like an array. So you can't directly set .className on the return and instead of:

document.getElementsByClassName(obj2).className = 'none';

You need:

var els = document.getElementsByClassName(obj2),
    i;
for (i = els.length - 1; i >= 0; i--)
   els[i].className = 'none';

// or if you know there will always be exactly one element returned:document.getElementsByClassName(obj2)[0].className = 'none',

The reason I've set the loop to count down is that a NodeList is supposed to be live, so if you start modifying the elements in the list they might disappear from the list and mess up your counter.

Post a Comment for "Javascript Changes One Some Class Names"