🚀 Ultimate JavaScript DOM Cheat Sheet (Free PDF) 👉 Get the PDF ×

JavaScript Tutorials

JavaScript

JavaScript Get Width Of Element new

JavaScript Change Background Color new

JavaScript CLASS Attribute

JavaScript GET Class Names new

JavaScript ADD Class To Element new

JavaScript CHANGE Class new

JavaScript TOGGLE Class new

JavaScript REMOVE Class From Element new

JavaScript Modules

JavaScript Import Function From Another File new

JavaScript Cannot use import statement outside a module new

JavaScript Defer or Async

JavaScript DOM

JavaScript Get Element By ID new

JavaScript Get Elements By Class Name new

JavaScript Get Elements By Tag Name new

JavaScript Get Elements By Name new

JavaScript HTMLCollection vs NodeList new

JavaScript append() new

JavaScript appendChild() new

JavaScript append() Vs appendChild() new

JavaScript Create HTML Element new

JavaScript Remove HTML Element new

JavaScript Functions

JavaScript Call A Function new

JavaScript Events

JavaScript Get ID of Clicked Element new

JavaScript e.target new

JavaScript Custom Pop-Up Modal Window new

JavaScript Make A Clicked Button Active new

JavaScript For Loop Click Event

JavaScript Images

JavaScript Create / Add Image

JavaScript Working With Images

JavaScript Image Slider

JavaScript Higher Order Functions

JavaScript Find()

JavaScript Filter() vs Find()

JavaScript Forms

JavaScript Radio Buttons

JavaScript Select Drop Down

JavaScript AJAX

JavaScript Fix CORS Error

JavaScript Menu

JavaScript Accordion Menu

JavaScript MVC

JavaScript MVC Part #1

JavaScript MVC Part #2

JavaScript MVC Part #3

Last modified on October 25th, 2022

Raja Tamil

6,183 views

0 Comments

Javascript

6,183

Learn how to get one or more CSS class names of an HTML element in JavaScript.

  1. Get Class Names Using classList
  2. Get Class Names Using getAttribute()
  3. Get Class Names Using className
  4. Get Class Name By its Index
  5. Get Class Name If it exists
  6. Get Class Names as a List

1. Get Class Names Using classList

Here is a simple div element that has two attributes: class and id.

<div class="shape orange" id="box">box</div>

HTML

Copy

Let’s see how to get the class names shape and orange of an element using the classList property.

First, get a DOM reference of an element using the getElementById() method on the document object.

The getElementById() method returns the div element object.

You can also use getElementsByClassName(), getElementsByTagName(), getElementsByName() to get DOM reference of one or more elements.

Assign it to a constant box.

Now, you can easily get all the class names by accessing the classList property on the element object.

const box = document.getElementById("box");
console.log(box.classList); // ['shape', 'orange', value: 'shape orange']
console.log(typeof box.classList); //DOMTokenList

JavaScript

Copy

It returns DOMTokenList which is an array-type object containing all the class names.

You can access any class name by its index value which is super useful.

2. Get Class Names Using getAttribute() Method

Alternatively, you can also use the getAttribute() method to get one or more class names of an element.

To do that, call the getAttribute() method on the box element object, passing the class name as an argument in quotes.

Unlike, the classList property, the getAttribute() will return a string containing all the class names.

Which is NOT that useful and I would always recommend using classList instead.

const box = document.getElementById("box");
console.log(box.getAttribute("class")); //  "shape orange"
console.log(typeof box.getAttribute("class")); //String

JavaScript

Copy

3. Get Class Names Using className Property

Similar to the getAttribute() method, you can also use the className property on the element object to get one or more class names in JavaScript.

Again, it will return the class name as a string type.

const box = document.getElementById("box");
console.log(box.className); //  "shape orange"
console.log(typeof box.className); //String

JavaScript

Copy

4. Get Class Name By Index

Sometimes, you may want to get a specific class name of an element by its position.

Here is the simple div element that has three class names: shape, orange and small.

<div class="shape orange small " id="box">box</div>

HTML

Copy

Let’s say I want to get the third class name small.

const box = document.getElementById("box");
console.log(box.classList); // ['shape', 'orange', 'small', value: 'shape orange small']
console.log(box.classList[2]); // "small"

JavaScript

Copy

Using the classList property on the element object, we can easily do that because it will return DOMTokenList which is an array-type object.

Finally, get the class name small by its index number which is 2.

Pretty straightforward.

5. Get Class Name If It Exists

Let’s check to see if a class name exists in an element before accessing it to avoid errors.

<div class="shape orange small" id="box">box</div>

HTML

Copy

Luckily, classList API has a method called contains() which does exactly that.

The contains() method takes an argument which is the class name that you want to check to see if it exists.

const box = document.getElementById("box");
console.log(box.classList.contains("small")); // true
console.log(box.classList.contains("blue")); // false

JavaScript

Copy

If it does, the contains() method returns true, otherwise false.

6. Get Class Names As A-List and Length

What if you want to get all the individual class names of an element in JavaScript?

As you know, the classList property on the element object will return the DOMTokenList which is an array-type object.

Loop through the DOMTokenList object using for…of and get individual class names on each iteration.

const box = document.getElementById("box");
for(const className of box.classList) {
  console.log(className); // 1.shape 2.orange 3.small
}

box.ClassList.length; //3

JavaScript

Copy

You may also like:

Disqus Recommendations

We were unable to load Disqus Recommendations. If you are a moderator please see our troubleshooting guide.

  • 3 years ago

Learn how to get use data from firebase 9 Cloud Firestore database with 3 …

  • 8 months ago

In this FREE course, you're going to learn how to build a simple real-world …

  • 3 years ago

Learn how to sign out or log out users of their current authentication using …

  • 3 years ago

Learn how to authenticate a user account using the …

  • 3 years ago
  • 1 comment

The onAuthStateChanged() method is triggered when a user's authentication state …

  • 3 years ago

Learn how to use createUserWithEmailAndPassword() to create a new Firebase …

  • 4 months ago

Learn how to model Firestore data the right way for performance, cost, and …

tempest.services.disqus.com

tempest.services.disqus.com is blocked

This page has been blocked by an extension

  • Try disabling your extensions.

ERR_BLOCKED_BY_CLIENT

Reload

This page has been blocked by an extension

Disqus Comments

We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

G

Start the discussion…

Comment

Log in with
or sign up with Disqus or pick a name

Disqus is a discussion network

  • Don't be a jerk or do anything illegal. Everything is easier that way.

Read full terms and conditions

This comment platform is hosted by Disqus, Inc. I authorize Disqus and its affiliates to:

  • Use, sell, and share my information to enable me to use its comment services and for marketing purposes, including cross-context behavioral advertising, as described in our Terms of Service and Privacy Policy, including supplementing that information with other data about me, such as my browsing and location data.
  • Contact me or enable others to contact me by email with offers for goods or services
  • Process any sensitive personal information that I submit in a comment. See our Privacy Policy for more information

Acknowledge I am 18 or older

  • 1

  • Discussion Favorited!

Favoriting means this is a discussion worth sharing. It gets shared to your followers' Disqus feeds, and gives the creator kudos!

Find More Discussions

Share

  • Tweet this discussion

    • Share this discussion on Facebook
    • Share this discussion via email
    • Copy link to discussion
  • Best

Be the first to comment.

Load more comments

live.rezync.com

live.rezync.com is blocked

This page has been blocked by an extension

  • Try disabling your extensions.

ERR_BLOCKED_BY_CLIENT

Reload

This page has been blocked by an extension

pippio.com

pippio.com is blocked

This page has been blocked by an extension

  • Try disabling your extensions.

ERR_BLOCKED_BY_CLIENT

Reload

This page has been blocked by an extension

Twitter Widget Iframe