Check if an element contains a class in JavaScript?

后端 未结 27 3073
面向向阳花
面向向阳花 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:16

    Just to add to the answer for people trying to find class names within inline SVG elements.

    Change the hasCLass() function to:

    function hasClass(element, cls) {
        return (' ' + element.getAttribute('class') + ' ').indexOf(' ' + cls + ' ') > -1;
      }
    

    Instead of using the className property you'll need to use the getAttribute() method to grab the class name.

提交回复
热议问题