简体   繁体   中英

Remove class from multiple elements in JavaScript or jQuery

Supposing I have this HTML with multiple elements and class.

How can I remove without naming the elements from all the element the class classToRemove ?

Thanks.


<html>
<body class="classToRemove">
    <div class="classToRemove">
        <a class="classToRemove">Link</a>
    <div>
</body>
<html>

使用 jQuery 真的很简单$('.classToRemove').removeClass('classToRemove');

Remove class using javascript

const removeClass = ($el, className) => {
  const _removeClass = function(el) {
    if (el.classList) {
      el.classList.remove(className);
    } else {
      el.className = el.className.replace(
        new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'),
        ' ',
      );
    }
  };
  if ($el.length === 1) {
    _removeClass($el);
  } else if ($el.length > 1) {
    $el.forEach(function(item) {
      _removeClass(item);
    });
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM