I have an element like this :
<span class="util bg-color-yellow tooltip bg-color-red"></span>
And I wanted to remove all class starting with "bg-color-", so I would simply loop thru all the class, then remove the matched ones :
var element = document.getElement......;
var elementClasses = element.classList;
for( var i = 0, l = elementClasses.length; i < l; i++ )
{
var className = elementClasses[i];
// console.log(i);
// console.log(name);
if( className.startsWith('bg-color-') )
{
element.classList.remove(className);
}
console.log('elementClasses contain :');
console.log(elementClasses);
}
When it matches the 'bg-color-' class, it successfully remove the class name, but it also edit the variable elementClasses
as if it's a reference to element.classList
, even if it's a variable ( copy ) of it.
1st loop :
elementClasses = [ util bg-color-yellow tooltip bg-color-red ]
2nd loop :
elementClasses = [ util bg-color-yellow tooltip bg-color-red ]
3nd loop :
elementClasses = [ util tooltip bg-color-red ]
There goes the problem! elementClasses
is modified on the same time as the elemnt.classList
is modified!
- How is that possible ?
- Is effectively
elementClasses
a sort of reference ofelement.classList
? - Did
elementClasses
recreated it self each timeelement.classList
is modified ?
.
Thank you very much! :)