javascriptmethodscall

Directly calling a method in JS works, but not with .call or .apply


I have a node resulting from a call

let node = document.getElementById('myID');

node is a Node, which has a classList object that has a remove() method

This works for me:

node.classList.remove('alert');

However, this does not work:

let method = node['classList']['remove'];
method.call(node, ['myclass']);

I receive the error in this second case:

Uncaught TypeError: 'remove' called on an object that does not implement interface DOMTokenList.

What am I doing wrong?


Solution

  • Your method refers to the remove function from DOMTokenList prototype (ie: from node.classList), so it expects its context (ie: this value) to be a DOMTokenList (node.classLIst), not just Element (ie: node):

    let method = node['classList']['remove'];
    method.call(node.classList, 'myclass');
    

    also note that passing an array as the second argument to .call() in this case will act as node.classList.remove(['myClass']), so you either need to use .apply() (if you want to pass an array which represents your arguments), or remove the array in this case.