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
Add a ment  | 

2 Answers 2

Reset to default 6

element.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.

本文标签: javascriptWhat is the difference between elementclassListcontains() and elementmatches()Stack Overflow