Tutorials References Menu

W3.JS Add Classes to HTML


Add a class:

w3.addClass(selector,'class')

Add multiple classes:

w3.addClass(selector,'class1 class2 class3...')

Add Class by Id

Add the "marked" class to an element with id="London":

Example

<button onclick="w3.addClass('#London','marked')">Add Class</button>

Try It Yourself » With CSS »


Add Class by Tag

Add the "marked" class to all <h2> elements:

Example

<button onclick="w3.addClass('h2','marked')">Add Class</button>

Try It Yourself » With CSS »


Add Class by Class

Add the "marked" class to an elements with class="city":

Example

<button onclick="w3.addClass('.city','marked')">Add Class</button>

Try It Yourself » With CSS »


Add Multiple Classes

To add multiple classes to an element, separate each class with a space.

Add both "class1" and "class2" to an element with id="London":

Example

<button onclick="w3.addClass('#London','class1 class2')">Add Classes</button>

Try It Yourself » With CSS »

Remove classes from HTML elements

Remove a class:

w3.removeClass(selector,'class')

Remove multiple classes:

w3.removeClass(selector,'class1 class2 class3...')

Remove Class by Id

Remove the "marked" class from an element with id="London":

Example

<button onclick="w3.removeClass('#London','marked')">Remove Class</button>

Try It Yourself » With CSS »


Remove Class by Tag

Remove the "marked" class from all <h2> elements:

Example

<button onclick="w3.removeClass('h2','marked')">Remove Class</button>

Try It Yourself » With CSS »


Remove Class by Class

Remove the "marked" class from all elements with class="city":

Example

<button onclick="w3.removeClass('.city','marked')">Remove Class</button>

Try It Yourself » With CSS »


Remove Multiple Classes

To remove multiple classes from an element, separate each class with a space.

Remove both "class1" and "class2" from an element with id="London":

Example

<button onclick="w3.removeClass('#London','class1 class2')">Remove Classes</button>

Try It Yourself » With CSS »

Toggle the Class of HTML elements

Toggle a class (on/off):

w3.toggleClass(selector,'class')

Toggle between two classes:

w3.toggleClass(selector,'property','class','class')

Toggle Class by Id

Toggle between the "marked" class of an element with id="London":

Example

<button onclick="w3.toggleClass('#London','marked')">Toggle</button>

Try It Yourself » With CSS »


Toggle Class by Tag

Toggle between the "marked" class of all <h2> elements:

Example

<button onclick="w3.toggleClass('h2','marked')">Toggle</button>

Try It Yourself » With CSS »


Toggle Class by Class

Toggle between the "marked" class of all elements with class="city":

Example

<button onclick="w3.toggleClass('.city','marked')">Toggle</button>

Try It Yourself » With CSS »


Toggle Multiple Classes

Toggle between the class name "class1" and "class2" of id="London:

Example

<button onclick="w3.toggleClass('#London','class1','class2')">Toggle</button>

Try It Yourself » With CSS »