MT IT
  • Introduction
  • KEEP IN MIND!!
  • 1️⃣1st month
    • Week 1
      • HTML/CSS
        • HTML
          • HTML Dasar
          • HTML Layouting
          • Learn More
            • Semantic HTML
            • Tables
            • Videos
            • Images
        • CSS
          • CSS Dasar
      • Weekly Review
    • Week 2
      • Bootstrap
        • Tutorial Bootstrap 5
      • Git & Github
      • Responsive
        • Responsive with Bootstrap 5
      • Weekly Review
    • Week 3
      • Javascript
        • Introduction to Javascript
          • What is JavaScript?
          • Brief History of JavaScript
          • How To Add JavaScript to HTML
        • All About Variables
          • Variables
          • Naming JavaScript Variables
          • JavaScript Naming Conventions
          • JavaScript Scope
        • Datatypes
          • What are data types?
          • Primitives and objects
          • Primitive data types
          • Object data types
          • TypeOf Operator
      • Weekly Review
    • Week 4
      • Javascript
        • Data Structures
          • Keyed Collections
          • Indexed collections
        • Equality Comparisons
        • Loops and Iterations
          • The for loop
          • do…while statement
          • while statement
      • Weekly Review
    • Monthly Review
  • 2️⃣2nd Month
    • Week 5
      • Javascript
        • Expressions and Operators
          • Basic operators, maths
          • Assignment operators
          • Comparison operators
          • Logical operators
          • String operators
          • Conditional (ternary) operator
          • Comma operator
        • JavaScript Function
        • Arrow function expressions
        • Built in functions
      • REST - Representational State Transfer
        • API - Application Programming Interface
        • Fetching data from the server
        • The Fetch API
        • Cross-Origin Resource Sharing (CORS)
      • Weekly Review
    • Week 6
      • DOM (Document Object Model)
        • DOM tree
        • Selecting elements
          • getElementById()
          • getElementsByName()
          • querySelector()
        • Manipulating elements
          • createElement()
          • appendChild()
          • textContent
        • Working with Attributes
          • Understanding Relationships Between HTML Attributes & DOM Object’s Properties
          • setAttribute()
          • getAttribute()
          • removeAttribute()
          • hasAttribute()
        • Manipulating Element’s Styles
          • JavaScript Style
          • getComputedStyle()
          • className
          • classList
          • Getting the Width and Height of an Element
        • Working with Events
          • JavaScript Events
          • Handling Events
          • Page Load Events
          • onload
          • Mouse Events
          • Keyboard Events
          • Scroll Events
          • scrollIntoView
      • React JS
        • Getting Started
        • Components Basics
          • Introducing JSX
          • Writing Markup with JSX
          • React Function Components
          • Props vs State
            • State: A Component's Memory
            • How to use Props in React
      • Working with APIs - 1
        • XMLHttpRequest
        • Fetch
      • Weekly Review
    • Week 7
      • Javascript
        • Asynchronous JavaScript
          • Asynchronous JavaScript For Dummies
            • (Pt1): Internals Disclosed!
            • (Pt2): Callbacks
            • (Pt3): Promises
            • (Pt4): Async/Await
        • Callback
        • Promises
          • Promises Basics
          • Promises Chaining
          • Promises Error Handling
        • Async/await
          • async function
        • Tutorial – Learn Callbacks, Promises, & Async/Await in JS by Making Ice Cream
      • React JS
        • Rendering
          • Conditional Rendering
          • Lists and Keys
          • Render Props
        • Hooks
          • useState
          • useEffect
      • Working with APIs - 2
        • Axios
      • React Router Dom
      • Weekly Review
    • Week 8
      • React JS
      • Responsive
      • Chakra UI
      • Firebase
        • Firebase Authentication
      • Weekly Review
    • Monthly Review
  • 3️⃣3rd month
    • Week 9
      • React JS
      • Chakra UI
      • Firebase
      • Axios
      • Weekly Review
    • Week 10
      • React JS
      • Boilerplate
      • Weekly Review
    • Week 11
      • Projects
      • Weekly Review
    • Week 12
      • Projects
      • Weekly Review
    • Project Review
  • 🏁FINAL REVIEW
  • 👇!! Learn More Below !!
  • 🥸Frontend Stack
    • 💻Web Dev
      • React JS
        • Reactstrap
        • React Icons
        • React Router Dom
      • Chakra UI
    • 📱Mobile Dev
      • React Native
        • Introduction
        • Page 1
      • Expo
      • Nativebase
    • 🎽CSS
      • Tailwind
      • Bootstrap
  • ☕Backend Stack
    • Node JS
    • Firebase
      • Authentication
      • Firestore
      • Storage
      • Hosting
      • Cloud Function
      • Emulators
      • RTDB
      • FCM
    • Google Cloud Platform
      • AppEngine
      • Big Query
      • Cloud Functions
      • Cloud Run
      • Cloud Scheduler
      • Cloud SQL
      • Logging
    • Object Relational Mapping (ORM)
      • Sequelize
    • MongoDB
      • MongoDB Realm
    • MySQL
      • Introduction
  • 🦸Fullstack
    • NEXT JS
    • LARAVEL
  • 📦Package
    • Middleware
      • Express JS
    • HTTP client
      • AXIOS
    • 📊Chart
      • Chart.js
      • JSCharting
      • React Google Chart
    • ⏳Date & Time
      • Moment JS
      • Day JS
    • 👨‍💻WYSIWYG Editor
      • Quill JS
      • Slate JS
Powered by GitBook
On this page
  • Introduction to JavaScript classList property
  • JavaScript classList examples
  1. 2nd Month
  2. Week 6
  3. DOM (Document Object Model)
  4. Manipulating Element’s Styles

classList

Introduction to JavaScript classList property

The classList is a read-only property of an element that returns a live collection of CSS classes:

const classes = element.classList;Code language: JavaScript (javascript)

The classList is a DOMTokenList object that represents the contents of the element’s class attribute.

Even though the classList is read-only, but you can manipulate the classes it contains using various methods.

JavaScript classList examples

Let’s take some examples of manipulating CSS classes of the element via the classList‘s interface.

1) Get the CSS classes of an element

Suppose that you have a div element with two classes: main and red.

<div id="content" class="main red">JavaScript classList</div>   
Code language: HTML, XML (xml)

The following code displays the class list of the div element in the Console window:

let div = document.querySelector('#content');
for (let cssClass of div.classList) {
    console.log(cssClass);
}Code language: JavaScript (javascript)

Output:

main
red

How it works:

  • First, select the div element with the id content using the querySelector() method.

  • Then, iterate over the elements of the classList and show the classes in the Console window.

2) Add one or more classes to the class list of an element

To add one or more CSS classes to the class list of an element, you use the add() method of the classList.

For example, the following code adds the info class to the class list of the div element with the id content:

let div = document.querySelector('#content');
div.classList.add('info');
Code language: JavaScript (javascript)

The following example adds multiple CSS classes to the class list of an element:

let div = document.querySelector('#content');
div.classList.add('info','visible','block');
Code language: JavaScript (javascript)

3) Remove element’s classes

To remove a CSS class from the class list of an element, you use the remove() method:

let div = document.querySelector('#content');
div.classList.remove('visible');Code language: JavaScript (javascript)

Like the add() method, you can remove multiple classes once:

let div = document.querySelector('#content');
div.classList.remove('block','red');Code language: JavaScript (javascript)

4) Replace a class of an element

To replace an existing CSS class with a new one, you use the replace() method:

let div = document.querySelector('#content');
div.classList.replace('info','warning');Code language: JavaScript (javascript)

5) Check if an element has a specified class

To check if the element has a specified class, you use the contains() method:

let div = document.querySelector('#content');
div.classList.contains('warning'); // trueCode language: JavaScript (javascript)

The contains() method returns true if the classList contains a specified class; otherwise false.

6) Toggle a class

If the class list of an element contains a specified class name, the toggle() method removes it. If the class list doesn’t contain the class name, the toggle() method adds it to the class list.

The following example uses the toggle() method to toggle the visible class of an element with the id content:

let div = document.querySelector('#content');
div.classList.toggle('visible');Code language: JavaScript (javascript)

Summary

  • The element’s classList property returns the live collection of CSS classes of the element.

  • Use add() and remove() to add CSS classes to and remove CSS classes from the class list of an element.

  • Use replace() method to replace an existing class with a new one.

  • Use contains() method to check if the class list of an element contains a specified class.

  • Use the toggle() method to toggle a class.

PreviousclassNameNextGetting the Width and Height of an Element

Last updated 1 year ago

2️⃣