Q:

How to Get Class List of an Element with jQuery

0

How to Get Class List of an Element with jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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:

<!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>
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:

<!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>
HTML

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
jQuery $(document).ready() Equivalent in JavaScrip... >>
<< How to Fix Uncaught ReferenceError: $ is not defin...