Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

element.classList returns an array of classes, its my understanding .includes() is used with arrays, so I don't understand why this wont work, I know I can use .contains() with classList but I'm curious as to why .includes() doesn't work.

both are arrays, if I typed this for example it wont work

var li=document.createElement('li'); li.classList.add('main-nav'); li.classList.includes('main-nav'); 

but this will

var ary=['a','b','c']; ary.includes('a');                                
like image 788
Brandon Avatar asked Jun 01 '16 10:06

Brandon


People also ask

What does the element classList toggle () method do?

toggle() The toggle() button is used for toggling classes to the element. It means adding a new class or removing the existing classes.

Does classList return an array?

classList returns an array of classes, its my understanding .

What is classList contains in Javascript?

classList is a read-only property that returns a live DOMTokenList collection of the class attributes of the element. This can then be used to manipulate the class list. Using classList is a convenient alternative to accessing an element's list of classes as a space-delimited string via element. className .

Can you add multiple classes with classList add?

classList property The classList property has add() and remove() methods that allow passing multiple classes as arguments. Let's say we have a button with id value of button . To add multiple classes, you'll need to pass each class as a separate parameter to the add method.


1 Answers

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 alternatively, 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.

like image 86
choz Avatar answered Oct 12 '22 04:10

choz