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

后端 未结 2 949
走了就别回头了
走了就别回头了 2020-12-30 21:20

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 k

相关标签:
2条回答
  • 2020-12-30 21:33

    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.

    0 讨论(0)
  • 2020-12-30 21:53

    The reason includes doesn't work is due to classList not being an array, but an array-like object. In this case it is a DOM Token List.

    You can convert an array-like object to an array by using the following:

    var liClasses = [].slice.apply(li.classList);
    

    or

    var liClasses = [...li.classList]; // es2015 syntax
    

    Otherwise, .includes() should be .contains(). See https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

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

    contains( String )

    Checks if specified class value exists in class attribute of the element.

    0 讨论(0)
提交回复
热议问题