DOM selection and manipulation using BEM (Block, Element, Modifier).
Install with npm
$ npm i bem.js --save
Code examples in es6, library is es5 compatible. See doc for full API documentation.
Selecting an element
import BEM from 'bem.js';
// Returns HTMLElement matching .block
BEM.getBEMNode('block');
// Returns HTMLElement matching .block--modifier
BEM.getBEMNode('block', false, 'modifier');
// Returns HTMLElement matching .block__element
BEM.getBEMNode('block', 'element');
// Returns HTMLElement matching .block__element--modifier
BEM.getBEMNode('block', 'element', 'modifier');
// Returns NodeList with HTMLElements matching .block__element--modifier
BEM.getBEMNodes('block', 'element', 'modifier');
// Returns HTMLElement matching .block__element--modifier, child of node
BEM.getChildBEMNode(node, 'block', 'element', 'modifier');
// Returns NodeList with HTMLElements matching .block__element--modifier, children of node
BEM.getChildBEMNodes(node, 'block', 'element', 'modifier');
Building BEM class names
import BEM from 'bem.js';
// Returns '.block'
BEM.getBEMSelector('block');
// Returns '.block.block--modifier'
BEM.getBEMSelector('block', false, 'modifier');
// Returns '.block__element'
BEM.getBEMSelector('block', 'element');
// Returns '.block__element.block__element--modifier'
BEM.getBEMSelector('block', 'element', 'modifier');
// Returns 'block'
BEM.getBEMClassName('block');
// Returns 'block--modifier'
BEM.getBEMClassName('block', false, 'modifier');
// Returns 'block__element'
BEM.getBEMClassName('block', 'element');
// Returns 'block__element--modifier'
BEM.getBEMClassName('block', 'element', 'modifier');
Adding/removing modifiers
import BEM from 'bem.js';
// Adding a modifier
let node = BEM.getBEMClassName('foo');
BEM.addModifier(node, 'bar'); // node.className is now 'foo foo--bar'
// Adding an additional modifier
BEM.addModifier(node, 'baz'); // node.className is now 'foo foo--bar foo--baz'
// Removing a modifier
BEM.removeModifier(node, 'bar'); // node.className is now 'foo foo--baz'
// Toggle a modifier
BEM.toggleModifier(node, 'bar');
// Add/remove modifier based on expression
BEM.toggleModifier(node, 'bar', exp); // If exp is true, add, remove otherwise
BEM.addModifier(node, 'bar', exp); // Only add if exp is true
BEM.removeModifier(node, 'bar'); // Only remove if exp is true
Check if HTMLElement has a modifier
import BEM from 'bem.js';
let node = BEM.getBEMNode('foo'); // <article class="foo foo--bar"></article>
BEM.hasModifier(node, 'bar') // true
BEM.hasModifier(node, 'baz') // false
let node = BEM.getBEMNode('foo'); // <article class="foo"></article>
BEM.hasModifier(node, 'bar') // false
$ gulp build // Make sure you test against the latest build
$ gulp lint // Check for linting errors
$ gulp test // Run the tests
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Maykin Media
Copyright © 2016 Maykin Media Licensed under the MIT license.