This happens because the value returned by Element.classList
is a DOMTokenList
, that despite having similar behaviors to array, does not always share the same behaviors.
An example of this is to perform a class change based on the index. If you do:
element.classList[0] = 'foo';
The class foo
will not be reflected, simply because this is not how the DOMTokenList
works.
That way, if you want to work with the classList
, will have to use one of the available methods.
Maybe the replace
do what you need. The problem is that you will exchange a class based on your value old, and not by the index. See:
const el = document.querySelector('div');
console.log(el.classList.value);
el.classList.replace('b', 'd');
console.log(el.classList.value);
<div class="a b c"></div>
If you really want to change a class by its index, it is possible to create a "gambiarra" for it. However, I do not recommend doing it, since DOMTokenList
is a "live list", that is, its value will be changed automatically whenever a class is changed.
Anyway, I’d be like this:
function changeClassByIndex(element, index, newClass) {
// Obtemos o valor da classe atual pelo índice:
const currentClass = element.classList.item(index);
// Trocamos a classe atual:
element.classList.replace(currentClass, newClass);
}
const el = document.querySelector('div');
console.log(el.classList.value); // a b c
changeClassByIndex(el, 1, 'd');
console.log(el.classList.value); // a d c
<div class="a b c"></div>
It was exactly what I expected the property to
classList
behaved as if it were an Array since it has how you return the class through the index without having to use specific methods for it.– marquinho
Yes, the problem is that if you change a value by the index, it will not be reflected in the DOM nor itself
DOMTokenList
.– Luiz Felipe
blz! Thank you :)
– marquinho