Tutorials References Menu

JS Reference

JS by Category JS by Alphabet

JavaScript

JS Array JS Boolean JS Classes JS Date JS Error JS Global JS JSON JS Math JS Number JS Operators JS RegExp JS Statements JS String

HTML DOM

DOM Attributes DOM Document DOM Element DOM Events DOM Event Objects DOM HTMLCollection DOM Location DOM Navigator DOM Screen DOM Style
alignContent alignItems alignSelf animation animationDelay animationDirection animationDuration animationFillMode animationIterationCount animationName animationTimingFunction animationPlayState background backgroundAttachment backgroundColor backgroundImage backgroundPosition backgroundRepeat backgroundClip backgroundOrigin backgroundSize backfaceVisibility border borderBottom borderBottomColor borderBottomLeftRadius borderBottomRightRadius borderBottomStyle borderBottomWidth borderCollapse borderColor borderImage borderImageOutset borderImageRepeat borderImageSlice borderImageSource borderImageWidth borderLeft borderLeftColor borderLeftStyle borderLeftWidth borderRadius borderRight borderRightColor borderRightStyle borderRightWidth borderSpacing borderStyle borderTop borderTopColor borderTopLeftRadius borderTopRightRadius borderTopStyle borderTopWidth borderWidth bottom boxShadow boxSizing captionSide caretColor clear clip color columnCount columnFill columnGap columnRule columnRuleColor columnRuleStyle columnRuleWidth columns columnSpan columnWidth counterIncrement counterReset cursor direction display emptyCells filter flex flexBasis flexDirection flexFlow flexGrow flexShrink flexWrap cssFloat font fontFamily fontSize fontStyle fontVariant fontWeight fontSizeAdjust height isolation justifyContent left letterSpacing lineHeight listStyle listStyleImage listStylePosition listStyleType margin marginBottom marginLeft marginRight marginTop maxHeight maxWidth minHeight minWidth objectFit objectPosition opacity order orphans outline outlineColor outlineOffset outlineStyle outlineWidth overflow overflowX overflowY padding paddingBottom paddingLeft paddingRight paddingTop pageBreakAfter pageBreakBefore pageBreakInside perspective perspectiveOrigin position quotes resize right scrollBehavior tableLayout tabSize textAlign textAlignLast textDecoration textDecorationColor textDecorationLine textDecorationStyle textIndent textOverflow textShadow textTransform top transform transformOrigin transformStyle transition transitionProperty transitionDuration transitionTimingFunction transitionDelay unicodeBidi userSelect verticalAlign visibility width wordBreak wordSpacing wordWrap widows zIndex
DOM Window

Web APIs

API Console API Geolocation API History API Storage

HTML Objects

<a> <abbr> <address> <area> <article> <aside> <audio> <b> <base> <bdo> <blockquote> <body> <br> <button> <canvas> <caption> <cite> <code> <col> <colgroup> <datalist> <dd> <del> <details> <dfn> <dialog> <div> <dl> <dt> <em> <embed> <fieldset> <figcaption> <figure> <footer> <form> <head> <header> <h1> - <h6> <hr> <html> <i> <iframe> <img> <ins> <input> button <input> checkbox <input> color <input> date <input> datetime <input> datetime-local <input> email <input> file <input> hidden <input> image <input> month <input> number <input> password <input> radio <input> range <input> reset <input> search <input> submit <input> text <input> time <input> url <input> week <kbd> <label> <legend> <li> <link> <map> <mark> <menu> <menuitem> <meta> <meter> <nav> <object> <ol> <optgroup> <option> <output> <p> <param> <pre> <progress> <q> <s> <samp> <script> <section> <select> <small> <source> <span> <strong> <style> <sub> <summary> <sup> <table> <tbody> <td> <tfoot> <th> <thead> <tr> <textarea> <time> <title> <track> <u> <ul> <var> <video>

Other References

CSSStyleDeclaration JS Conversion


HTML DOM classList Property

❮ Element Object

Example

Add the "mystyle" class to a <div> element:

document.getElementById("myDIV").classList.add("mystyle");
Try it Yourself »

More "Try it Yourself" examples below.


Definition and Usage

The classList property returns the class name(s) of an element, as a DOMTokenList object.

This property is useful to add, remove and toggle CSS classes on an element.

The classList property is read-only, however, you can modify it by using the add() and remove() methods.

Cross-browser solution: The classList property is not supported in IE9 and earlier. However, you can use the className property or regular expressions for a cross-browser solution (see "More Examples" on the bottom of this page).


Browser Support

The numbers in the table specify the first browser version that fully supports the property.

Property
classList 8.0 10.0 3.6 5.1 11.5

Syntax

element.classList

Properties

Property Description
length Returns the number of classes in the list.

This property is read-only

Methods

Method Description
add(class1, class2, ...) Adds one or more class names to an element.

If the specified class already exist, the class will not be added
contains(class) Returns a Boolean value, indicating whether an element has the specified class name.

Possible values:

  • true - the element contains the specified class name
  • false - the element does not contain the specified class name
item(index) Returns the class name with a specified index number from an element. Index starts at 0.

Returns null if the index is out of range
remove(class1, class2, ...) Removes one or more class names from an element.

Note: Removing a class that does not exist, does NOT throw an error
toggle(class, true|false) Toggles between a class name for an element.

The first parameter removes the specified class from an element, and returns false.
If the class does not exist, it is added to the element, and the return value is true.

The optional second parameter is a Boolean value that forces the class to be added or removed, regardless of whether or not it already existed. For example:

Remove a class: element.classList.toggle("classToRemove", false);
Add a class: element.classList.toggle("classToAdd", true);

Note: The second parameter is not supported in Internet Explorer or Opera 12 and earlier.


Technical Details

Return Value: A DOMTokenList, containing a list of the class name(s) of an element

More Examples

Example

Add multiple classes to a <div> element:

document.getElementById("myDIV").classList.add("mystyle", "anotherClass", "thirdClass");
Try it Yourself »

Example

Remove a class from a <div> element:

document.getElementById("myDIV").classList.remove("mystyle");
Try it Yourself »

Example

Remove multiple classes from a <div> element:

document.getElementById("myDIV").classList.remove("mystyle", "anotherClass", "thirdClass");
Try it Yourself »

Example

Toggle between two classes for a <div> element:

document.getElementById("myDIV").classList.toggle("newClassName");
Try it Yourself »

Example

Get the class name(s) of a <div> element:

<div id="myDIV" class="mystyle anotherClass thirdClass">I am a DIV element</div>

var x = document.getElementById("myDIV").classList;
Try it Yourself »

Example

Find out how many class names a <div> element has:

var x = document.getElementById("myDIV").classList.length;
Try it Yourself »

Example

Get the first class name (index 0) of a <div> element:

var x = document.getElementById("myDIV").classList.item(0);
Try it Yourself »

Example

Find out if an element has a "mystyle" class:

var x = document.getElementById("myDIV").classList.contains("mystyle");
Try it Yourself »

Example

Find out if an element has a "mystyle" class. If so, remove another class name:

var x = document.getElementById("myDIV");

if (x.classList.contains("mystyle")) {
  x.classList.remove("anotherClass");
} else {
  alert("Could not find it.");
}
Try it Yourself »

Example

Toggle between classes to create a dropdown button:

// Get the button, and when the user clicks on it, execute myFunction
document.getElementById("myBtn").onclick = function() {myFunction()};

/* myFunction toggles between adding and removing the show class, which is used to hide and show the dropdown content */
function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}
Try it Yourself »

Fallback Example: add

A cross-browser solution when using the classList.add() method, for IE9 and earlier:

var x, name, arr;
x = document.getElementById("myDIV");
if (x.classList) {
  x.classList.add("mystyle");
} else {
  name = "mystyle";
  arr = x.className.split(" ");
  if (arr.indexOf(name) == -1) {
    x.className += " " + name;
  }
}
Try it Yourself »

Fallback Example: remove

A cross-browser solution when using the classList.remove() method, for IE9 and earlier:

var x = document.getElementById("myDIV");

if (x.classList) {
  x.classList.remove("mystyle");
} else {
  x.className = x.className.replace(/\bmystyle\b/g, ""); // For IE9 and earlier
}
Try it Yourself »

Fallback Example: contains

A cross-browser solution when using the classList.contains() method, for IE9 and earlier:

var x = document.getElementById("myDIV");

if (x.classList) {
  alert(x.classList.contains("mystyle"));
} else {
  alert(/\bmystyle\b/g.test(x.className)); // For IE9 and earlier
}
Try it Yourself »

Fallback Example: toggle

A cross-browser solution when using the classList.toggle() method, for IE9:

var x = document.getElementById("myDIV");

if (x.classList) {
  x.classList.toggle("mystyle");
} else {
  // For IE9
  var classes = x.className.split(" ");
  var i = classes.indexOf("mystyle");

  if (i >= 0)
    classes.splice(i, 1);
  else
    classes.push("mystyle");
    x.className = classes.join(" ");
}
Try it Yourself »

Example

Create a sticky navigation bar:

// Get the navbar
var navbar = document.getElementById("navbar");

// Get the offset position of the navbar
var sticky = navbar.offsetTop;

// Add the sticky class to the navbar when you reach its scroll position. Remove the sticky class when you leave the scroll position.
function myFunction() {
  if (window.pageYOffset  >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}
Try it Yourself »

Related Pages

CSS Tutorial: CSS Syntax

CSS Reference: CSS .class Selector

HTML DOM Reference: HTML DOM className Property

HTML DOM Reference: HTML DOM getElementsByClassName() Method

HTML DOM Reference: HTML DOM Style Object


❮ Element Object