WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Get Class Name Using jQuery

Topic: JavaScript / jQueryPrev|Next

Answer: Use the jQuery attr() Method

You can simply use the attr() method to get or retrieve the class name of an element using jQuery.

Let's try out the following example to understand how it basically works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Class Name of an Element</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            var className = $("#test").attr("class");
            alert(className); // Outputs: hint
        });
    });
</script>
</head>
<body>
    <div id="test" class="hint">Click the following button to get the class name of this div element.</div>
    <button type="button">Get Class Name</button>
</body> 
</html>

Similarly, if you want to get the ID name of an element you can use attr("id") method.


Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties