Check if an element contains a class in JavaScript?

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

    This is supported on IE8+.

    First we check if classList exists if it does we can use the contains method which is supported by IE10+. If we are on IE9 or 8 it falls back to using a regex, which is not as efficient but is a concise polyfill.

    if (el.classList) {
      el.classList.contains(className);
    } else {
      new RegExp('(^| )' + className + '( |$)', 'gi').test(el.className);
    }
    

    Alternatively if you are compiling with babel you can simply use: el.classList.contains(className);

提交回复
热议问题