Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
392 views
in Technique[技术] by (71.8m points)

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

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');                               
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...