jQuery
jQuery Get Class Examples
Have you wanted to get class of an element or list of all class applied to an element using jQuery? In this article, I am going to share an easy way to do just that. Actual code is just 1 line, so it’s super easy to follow along.
Examples on using jQuery to Get Class
The following example assumes that there is a div with ID “my_div” and a list of all class applied to this div should be alerted, when “Get class” button is clicked.
Example: Using jQuery to get div class
<html>
<head>
<title>jQuery Get Class | Get All Class applied to an element using jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>
<body>
<div id="my_div" class="Lorem ipsum dolor_spec sit amet">Hello World!</div>
<input type="submit" name="get" id="get" value="Get Class" />
<script type="text/javascript">
$('#get').click(function() {
alert( $("#my_div").attr("class") );
});
</script>
</body>
</html>Simple, isn’t it?
Do you know of any other ways to get class or get all class list applied to an element using jQuery? Feel free to suggest by commenting below.
This is good. But how to select multiple class?
September 7, 2012 at 1:15 pm
Hi Vasu,
Do you mean how to get multiple classes so that you can use it in your code? If yes, you can simply assign the values to a var and use it in your code, instead of alerting it. Hope this answers your question.
Robert
September 11, 2012 at 8:43 pm