Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

classList.toggle('class', true) vs classList.add

Tags:

javascript

As the title says. I can't seem to see the difference between the two, and I can't seem to see the point of the second argument for toggle.

Can someone explain to me?

like image 799
BigName Avatar asked Dec 19 '22 04:12

BigName


2 Answers

There is no difference; the second argument to toggle is to make this kind of thing more convenient:

if (hide) {
    el.classList.add('hidden');
} else {
    el.classList.remove('hidden');
}

as:

el.classList.toggle('hidden', hide);
like image 87
Ry- Avatar answered Jan 01 '23 01:01

Ry-


https://dom.spec.whatwg.org/#interface-domtokenlist :

If force is not given, "toggles" token, removing it if it’s present and adding it if it’s not. If force is true, adds token (same as add()). If force is false, removes token (same as remove()). Returns true if token is now present, and false otherwise.

I think the spec is clear enough.

like image 38
Touffy Avatar answered Jan 01 '23 02:01

Touffy