Pergunta

ok, i have class 1, and i want to add another class style (class2) to this class 1.

how i do this?

and why this works:

document.getElementById("idteste").className += ' HighAsuka';

and this not?

document.getElementsByClassName('class1').className += ' class2';
Foi útil?

Solução

As others have pointed out, the difference is getElementById returns a single element, whereas getElementsByClassName yields a collection of elements. On a single elements you can use .className as it is a property of that element.

Now to answer your main question; in order to add class2 to all elements which have class1 you do this:

var elements = document.getElementsByClassName('class1');
for(i = 0; i < elements.length; i++) {
    elements[i].className += ' class2';
}

Outras dicas

getElementsByClassName returns a list of elements as you can see from Elements in getElementsByClassName

So you need to access the array element and then set class name

document.getElementsByClassName('class')[0].className
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top