How to Get Class List of an Element with jQuery
Topic: JavaScript / jQueryPrev|Next
Answer: Use the jQuery attr()
Method
You can simply use the attr()
method to get the class list i.e. list of all the classes that are assigned to an element using jQuery. The class names are space separated.
Let's take a look at the following example to understand how it actually works:
Example
Try this code »<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Class List for Element</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
// Get class list string
var classList = $("#myDiv").attr("class");
// Creating class array by splitting class list string
var classArr = classList.split(/\s+/);
$.each(classArr, function(index, value){
$("body").append("<p>" + index + ": " + value + "</p>");
});
});
});
</script>
</head>
<body>
<div id="myDiv" class="foo bar bazz">
<p>This is a paragraph inside DIV element</p>
</div>
<button type="button">Get Div Class List</button>
</body>
</html>
Alternatively, you can also get the class list in JavaScript using the DOM element's classList
property like document.getElementById("myDiv").classList;
Let's try out the following example to understand how it basically works:
Example
Try this code »<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get List of Classes from an Element</title>
<script>
function getClasses(){
var classList = document.getElementById("myDiv").classList;
for(var i = 0; i < classList.length; i++){
document.body.insertAdjacentHTML("beforeend", "<p>" + classList[i] + "</p>");
}
}
</script>
</head>
<body>
<div id="myDiv" class="foo bar bazz">
<p>This is a paragraph inside DIV element</p>
</div>
<button type="button" onclick="getClasses();">Get Div Class List</button>
</body>
</html>
Related FAQ
Here are some more FAQ related to this topic: