Read more

jQuery: How to remove classes from elements using a regular expression

Arne Hartherz
November 05, 2018Software engineer at makandra GmbH

jQuery's removeClass removes the given class string from an element collection. If you want to remove multiple/unknown classes matching a given pattern, you can do that.

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

For example, consider a DOM node for the following HTML. We'll reference it by $element below.

<div class="example is-amazing is-wonderful"></div>

Option A: Selecting classes, then removing them

You can iterate over existing classes, and select matching ones. The example below is ES6, on ES5 could write something similar using jQuery.grep.

let classes = Array.from($element.prop('classList'))
let existingModifiers = classes.filter(className => { return className.match(/^is-/) })

$layout.removeClass(existingModifiers.join(' '))

Note that classList is native DOM API and returns a DOMTokenList (not an Array) of element classes.

Option B: Using a matcher function

Since jQuery 1.4 (read: forever) you may pass a function that disects an element's class, and returns a string that will then be removed through the "classic" string approach. It's a bit awkward to use.

If we now want to remove those "is-" modifiers, and we don't know what they will be, we can remove them like so:

function modifierClassMatcher(index, className) {
  let matchedClasses = className.match(/(^|\s)is-\S+/g)
  return (matchedClasses || []).join('')
}

$element.removeClass(modifierClassMatcher)

The modifierClassMatcher function will look for any class names starting with "is-". We use ^ and \s to split the class attribute string and find all class names.
The function then returns the string to remove, in the example above " is-amazing is-wonderful".

Posted by Arne Hartherz to makandra dev (2018-11-05 11:46)