Get CSS class of an element with JavaScript/jQuery
This post will discuss how to get the CSS class of an element using JavaScript and jQuery.
1. Using jQuery
You can get the value of class attribute using jQuery’s .attr() method.
JS
|
1 2 3 4 |
$(document).ready(function() { var className = $('#container').attr('class'); alert(className); }); |
CSS
|
1 2 3 4 5 |
.outerclass { font-size: 14px; margin: 10px; padding: 3px; } |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container" class="outerclass"></div> </body> </html> |
Alternatively, you can use jQuery’s .prop() method.
JS
|
1 2 3 4 |
$(document).ready(function() { var className = $('#container').prop('class'); alert(className); }); |
CSS
|
1 2 3 4 5 |
.outerclass { font-size: 14px; margin: 10px; padding: 3px; } |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container" class="outerclass"></div> </body> </html> |
2. Using JavaScript
In plain JavaScript, you can use the className property to get the value of the class attribute of the specified element.
JS
|
1 2 |
var className = document.getElementById("container").className; alert(className); |
CSS
|
1 2 3 4 5 |
.outerclass { font-size: 14px; margin: 10px; padding: 3px; } |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container" class="outerclass"></div> </body> </html> |
In modern browsers, you can get value of className like:
JS
|
1 2 |
const { className } = document.querySelector('#container'); alert(className); |
CSS
|
1 2 3 4 5 |
.outerclass { font-size: 14px; margin: 10px; padding: 3px; } |
HTML
|
1 2 3 4 5 6 |
<!doctype html> <html lang="en"> <body> <div id="container" class="outerclass"></div> </body> </html> |
That’s all about getting the CSS class of an element using 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 :)