Class attribute

These methods inspect and manipulate the CSS classes assigned to elements.

addClass

Adds the specified class(es) to each element in the set of matched elements.

Add single class

jQuery

element.addClass('foo');

Vanilla JS

element.classList.add('foo');

Add multiple classes

jQuery

element.addClass('a b c');

Vanilla JS

element.classList.add('a', 'b', 'c');

Add class to the set of elements

jQuery

elements.addClass('foo');

Vanilla ES6+

elements.forEach(x => x.classList.add('foo'));

Vanilla ES5

elements.forEach(function(element) {
    element.classList.add('foo');
});

removeClass

Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

Remove single class

jQuery

element.removeClass('foo');

Vanilla JS

element.classList.remove('foo');

Remove multiple classes

jQuery

element.removeClass('a b c');

Vanilla JS

element.classList.remove('a', 'b', 'c');

Remove class from the set of elements

jQuery

elements.removeClass('foo');

Vanilla ES6+

elements.forEach(x => x.classList.remove('foo'));

Vanilla ES5

elements.forEach(function(element) {
    element.classList.remove('foo');
});

toggleClass

Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.

Toggle class

jQuery

element.toggleClass('foo');

Vanilla JS

element.classList.toggle('foo');

Conditionally toggle class

jQuery

element.toggleClass('foo', true);
element.toggleClass('foo', false);

Vanilla JS

element.classList.toggle('foo', true);
element.classList.toggle('foo', false);

Toggle class on the set of elements

jQuery

elements.toggleClass('foo');

Vanilla ES6+

elements.forEach(x => x.classList.toggle('foo'));

Vanilla ES5

elements.forEach(function(element) {
    element.classList.toggle('foo');
});

hasClass

Determine whether any of the matched elements are assigned the given class.

Check if single element has certain class

jQuery

var has = element.hasClass('foo');

Vanilla JS

var has = element.classList.contains('foo');

Check if at least one of elements in the set has certain class

jQuery

var has = elements.hasClass('foo');

Vanilla ES6+

var has = elements.some(x => x.classList.contains('foo'));

Vanilla ES5

var has = elements.some(function(element) {
    return element.classList.contains('foo');
});
shopify traffic stats