Why doesn’t .includes() work with .classList?

Element.classList is a DOMTokenList object, though it prints an array-like in console. But if you try on Firefox, it’d return DOMTokenList["main-nav"]

And, includes is a method of Array instead of DOMTokenList.

Which is why it’s expected to encounter li.classList.includes is not a function in your case.

You can use ES2015 spread operator to cast it to be an array.

[...li.classList].includes('main-nav')

Or, you can also use Array.from to cast it to be an array.

Array.from(li.classList).includes('main-nav')

Or no-hassle alternative, you can use DOMTokenList.contains method.

li.classList.contains('main-nav')

Why is it declared as includes instead of has or contains? (thanks to @akinuri)

Quoting from the proposal

The web has classes like DOMStringList and DOMTokenList
which are array-like, and have methods named contains with the
same semantics as our includes. Unfortunately, meshing with those
is not web-compatible.

Leave a Comment

404 Not Found

Not Found

The requested URL was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.