Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all CSS classes of an element?

I have an element with multiple classes and I'd like to get its css classes in an array. How would I do this? Something like this:

var classList = $(this).allTheClasses(); 
like image 222
frenchie Avatar asked Feb 14 '12 15:02

frenchie


People also ask

How do I see all classes in CSS?

Focus that input and hit Ctrl + Space. A pick list of all class styles in the current opened document should appear.

How do I get all the CSS properties of an element?

The CSS of an element can be obtained using the getComputedStyle element function in JavaScript. It returns a JavaScript object containing CSS properties and their values. This object is indexed and iterable over the property names. The getPropertyValue(property) is used to get the value of a property.

Can an element have multiple CSS classes?

An element is usually only assigned one class. The corresponding CSS for that particular class defines the appearance properties for that class. However, we can also assign multiple classes to the same element in CSS.

How do you select all classes in HTML?

To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)


2 Answers

No need to use jQuery for it:

var classList = this.className.split(' ') 

If you for some reason want to do it from a jQuery object, those two solutions work, too:

var classList = $(this)[0].className.split(' ') var classList = $(this).prop('className').split(' ') 

Of course you could switch to overkill development mode and write a jQuery plugin for it:

$.fn.allTheClasses = function() {     return this[0].className.split(' '); } 

Then $(this).allTheClasses() would give you an array containing the class names.

like image 142
ThiefMaster Avatar answered Oct 05 '22 23:10

ThiefMaster


Note that you can also use myElement.classList as a simple array-like object:

const classList = myElement.classList; 

This is supported by all major browsers for a while now, apart IE 9 and below.

like image 33
Javarome Avatar answered Oct 06 '22 00:10

Javarome