Search code examples
javascriptdomdomtokenlist

.apply throwing exception when applied with classList.remove


I was trying something and faced this issue. When you try to do element.classList.remove.apply, it throws error:

Uncaught TypeError: Illegal invocation

You can test it using following snippet.

var div = document.querySelector('.test');
var classesToRemove = ['test1', 'test2', 'test3'];
div.classList.remove.apply(div, classesToRemove);
.test {
  width: 100px;
  height: 100px;
}

.test1 {
  color: blue
}

.test2 {
  background: gray;
}

.test3 {
  border: 1px solid gray;
}
<div class='test test1 test2 test3'>Test</div>


Note: I'm aware that I can solve this using spread operator(...), but I'm more interested in understanding why this fails.


Solution

  • You can definitely use Function.prototype.apply here too, however correct context for invocation is div.classList object, not HTMLElement div itself.

    Try this:

    var div = document.querySelector('.test');
    var classesToRemove = ['test1', 'test2', 'test3'];
    div.classList.remove.apply(div.classList, classesToRemove);
    .test {
      width: 100px;
      height: 100px;
    }
    
    .test1 {
      color: blue
    }
    
    .test2 {
      background: gray;
    }
    
    .test3 {
      border: 1px solid gray;
    }
    <div class='test test1 test2 test3'>Test</div>