Table of Contents

<HTMLElement>.addClass()

Attaches a class to an HTMLElement.

Usage
HTMLElement = Element.addClass(className)
Member of:
HTMLElement
Parameter:
className – the name of the class to add as String object, or quoted string (required).
Returns:
The same HTMLElement that it was called on, thus allowing for command chaining.
Notes:
  • If the class to be added already exists, this method will do nothing.
  • This method is a simple wrapper for the basic classList.add() function. The only difference is that this function returns the HTMLElement and thus allows chaining other functions for neater and/or more compact code.

Examples

Simple example:

let foo = document.getElementById('foo');
foo.addClass('bar');

Chaining methods allows for very compact code:

document.getElementById('foo').addClass('bar').attr('data-value', '123');

… that can also look very neat and readable:

document.getElementById('foo')
	.addClass('bar')
	.attr('data-value', '123')
;

See also

More information