Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass class function as function parameter JS

I have defined following function:

function handleMessageDot(fun) {
    domElement.classList.fun('hidden');
}

Now I want to use one of those:
handleMessageDot(add), handleMessageDot(remove).
I get remove is not defined error. I assume that is because remove() and add() functions are classList methods.
I now I can do the following:

function handleMessageDot(domElement, fun) {
    domElement.classList.fun('hidden');
}

but I don’t want to do that.
Is there a way to do ‘my’ way?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

When attempting to access the property of an object using the value of a separate variable you need to use array notation:

const handleMessageDot = (domElement, fun) => domElement.classList[fun]('hidden');

handleMessageDot(document.querySelector('.hidden'), 'remove');
.hidden {
  display: none;
}
<div class="hidden">
  Lorem ipsum
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading