Check if an element contains a class in JavaScript?

后端 未结 27 2745
面向向阳花
面向向阳花 2020-11-22 09:36

Using plain JavaScript (not jQuery), Is there any way to check if an element contains a class?

Currently, I\'m doing this:

27条回答
  •  时光取名叫无心
    2020-11-22 10:22

    Element.matches()

    element.matches(selectorString)

    According to MDN Web Docs:

    The Element.matches() method returns true if the element would be selected by the specified selector string; otherwise, returns false.

    Therefore, you can use Element.matches() to determine if an element contains a class.

    const element = document.querySelector('#example');
    
    console.log(element.matches('.foo')); // true

    View Browser Compatibility

提交回复
热议问题