Skip to content

Instantly share code, notes, and snippets.

@smichaelsen
Last active April 16, 2022 15:20
Show Gist options
  • Save smichaelsen/a2804c9809e90e484531eebd1b3ca98e to your computer and use it in GitHub Desktop.
Save smichaelsen/a2804c9809e90e484531eebd1b3ca98e to your computer and use it in GitHub Desktop.
Add/Remove BEM Modifier with classList
DOMTokenList.prototype.getFullModifierClassName = function (modifier) {
if (this.length === 0) {
return '';
}
return this.item(0) + '--' + modifier;
};
DOMTokenList.prototype.addModifier = function (modifier) {
this.add(this.getFullModifierClassName(modifier));
};
DOMTokenList.prototype.removeModifier = function (modifier) {
this.remove(this.getFullModifierClassName(modifier));
};
DOMTokenList.prototype.toggleModifier = function (modifier, forceValue) {
const fullModifierClassName = this.getFullModifierClassName(modifier);
if (forceValue === undefined) {
this.toggle(fullModifierClassName);
} else if (forceValue) {
this.add(fullModifierClassName);
} else {
this.remove(fullModifierClassName);
}
};
const element = document.querySelector('.my-block__element');
element.classList.addModifier('funky'); // -> adds the class .my-block__element--funky
// It is assumed that the first class of the element is its block or element name.
// E.g.
// <div class="my-block__element some other classes">
// The first class "my-block__element" will be used to create the modifier class.
@vasartam
Copy link

Great snippet, thanks for sharing!

Here is the method for checking if element already has a BEM modifier:

DOMTokenList.prototype.hasModifier = function (modifier) {
    return this.contains(this.getFullModifierClassName(modifier));
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment