Skip to content
Advertisement

while updating class name of an element why “this” keyword is needed?

I’m referring to example

JavaScript
JavaScript
JavaScript

In this to replace active class to nil, current[0].className is used as below

JavaScript

But to add classname, this keyword is used

JavaScript

Why can’t I add new classname as below

current[0].className += " active"; ?

Advertisement

Answer

Because this in your current context is the clicked button. Another way to do it is with e.target.classList.add('active');, but before doing so you should pass e to the callback function parameter like that

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement