Get class name of an element with JavaScript/jQuery
This post will discuss how to get the class name of an element in JavaScript and jQuery.
1. Using jQuery
A simple and fairly efficient solution to getting the value of an element’s class attribute is to use jQuery’s .attr() method. This method is demonstrated below:
jQuery
|
1 2 3 4 |
$(document).ready(function() { var className = $('#container').attr('class'); alert(className); }); |
HTML
|
1 |
<div id="container" class="some-class"></div> |
CSS
|
1 2 3 |
.some-class { font: 15px 'Exo 2', sans-serif; } |
Alternatively, you can directly access the className property, which represents the contents of the element’s class attribute.
jQuery
|
1 2 3 4 |
$(document).ready(function() { var className = $('#container')[0].className; alert(className); }); |
HTML
|
1 |
<div id="container" class="some-class"></div> |
CSS
|
1 2 3 |
.some-class { font: 15px 'Exo 2', sans-serif; } |
2. Using JavaScript
In plain JavaScript, you can get the value of the class attribute of the specified element with className property, as shown below:
JS
|
1 2 |
var className = document.getElementById('container').className; alert(className); |
HTML
|
1 |
<div id="container" class="some-class"></div> |
CSS
|
1 2 3 |
.some-class { font: 15px 'Exo 2', sans-serif; } |
Alternatively, you can use the querySelector() method like below.
JS
|
1 2 |
const { className } = document.querySelector('#container'); alert(className); |
HTML
|
1 |
<div id="container" class="some-class"></div> |
CSS
|
1 2 3 |
.some-class { font: 15px 'Exo 2', sans-serif; } |
That’s all about getting the class name of an element in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)