Last active
          April 16, 2022 15:20 
        
      - 
      
 - 
        
Save smichaelsen/a2804c9809e90e484531eebd1b3ca98e to your computer and use it in GitHub Desktop.  
    Add/Remove BEM Modifier with classList
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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); | |
| } | |
| }; | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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. | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Great snippet, thanks for sharing!
Here is the method for checking if element already has a BEM modifier: