BEM in JavaScript: Selecting and Manipulating Classes
You'll learn why BEM class names are perfect targets for JavaScript and how to select elements without fragile structural dependencies.
The Problem with Structure-Based Selection
Imagine you wrote document.querySelector('.header nav ul li a'). This selector breaks if you change your HTML structure — maybe you remove the <ul> or nest things differently. Your JavaScript is now coupled to your HTML structure, making refactoring risky.
BEM Classes as Stable Selectors
BEM class names are stable contracts between your HTML, CSS, and JavaScript. Because each class is unique and meaningful, you can select elements by their purpose, not their position in the DOM tree.
Instead of structural selectors, you target the specific BEM class:
// Fragile - breaks if structure changes
const menuLink = document.querySelector('.header nav ul li a');
// Robust - works regardless of structure
const menuLink = document.querySelector('.menu__link');
Selecting Blocks, Elements, and Modifiers
You can reliably target any part of your BEM component:
// Select the entire block
const menu = document.querySelector('.menu');
// Select all elements within that block
const menuItems = document.querySelectorAll('.menu__item');
// Target a specific modifier state
const activeLink = document.querySelector('.menu__link--active');
Adding and Removing Modifiers
JavaScript often needs to toggle states. With BEM, you manipulate modifier classes without touching the base classes:
const button = document.querySelector('.button');
// Add a modifier
button.classList.add('button--loading');
// Toggle a modifier
button.classList.toggle('button--disabled');
// Remove a modifier
button.classList.remove('button--loading');
Key Takeaway: BEM class names serve as reliable, structure-independent selectors for JavaScript, making your code resilient to HTML changes while maintaining clear semantic meaning.