Q:

How to Get Class Name Using jQuery

0

How to Get Class Name Using 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 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.

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
How to Sleep Before Continuing in JavaScript... >>
<< How to Preview an Image Before it is Uploaded Usin...