admin管理员组文章数量:1430027
In JavaScript you can check whether an element has a specific class by using the following options:
Option 1
element.classList.contains('someClass');
Option 2
This option also allows to check for multiple classes where as option 1 does not (would require separate check for each class)
element.matches('.someClass');
Question
Which option should be used when and are the any other differences between them other than mentioned? Which one is less expensive?
In JavaScript you can check whether an element has a specific class by using the following options:
Option 1
element.classList.contains('someClass');
Option 2
This option also allows to check for multiple classes where as option 1 does not (would require separate check for each class)
element.matches('.someClass');
Question
Which option should be used when and are the any other differences between them other than mentioned? Which one is less expensive?
Share Improve this question asked Oct 14, 2019 at 8:39 BambiOurLordBambiOurLord 3725 silver badges12 bronze badges 1- 1 One is more generic than the other. "Which one is less expensive?" Benchmark them! Although it's very likely it doesn't matter. – VLAZ Commented Oct 14, 2019 at 8:41
2 Answers
Reset to default 6element.matches
allows for a much more flexible test.
If you only need to check if an element has or doesn't have one particular class, feel free to use contains
. But if you want to do additional checking based on what CSS selectors the element can match, .matches
allows for a much more concise method of achieving that goal. For example:
element.matches('a.someClass.foo')
will return true
if element
is an anchor element, which has a someClass
class, and also has a foo
class.
element.matches('.someClass[data-num="3"]:hover')
will return true
if element
has a someClass
class, has a data-num
attribute of 3, and is being hovered.
Expense doesn't matter - the performance cost is next to nothing regardless.
The matches() method checks to see if the Element would be selected by the provided selectorString -- in other words -- checks if the element "is" the selector. Source: mozilla
Matches is not testing only classes but whole selector (any attribute of element). For example you can use it for data attributes:
element.matches('[data-anything="value"]')
classlist.contains()
is only for classes.
Which one is less expensive?
Personally I think it doesn't matter but in theory contains()
should be less expensive because it's targeting only one specific attribute.
版权声明:本文标题:javascript - What is the difference between element.classList.contains() and element.matches() - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745555825a2663178.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论