Get class name of any element in jquery

In this programming tutorial we will learn how to get class name of any element in jquery. It is quite easy in jquery by utilizing its built-in attr() function. This attr() function is quite handy. Let's have a look over the following code snippet.
Get class name of any element in jquery
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
.divclass{
font-family:verdana;
font-size:12px;
color:green;
}
</style>
</head>
<body>
	<div id="myDiv" class="divclass">Welcome to nice-tutorials.blogspot.com</div><br/>
	<span></span>
<script language="javascript" type="text/javascript">
var divClassName=$("#myDiv").attr("class");
$("span").html("Div's class is <strong>"+divClassName+"</strong>")
</script>
</body>
</html>

Output:-
Welcome to nice-tutorials.blogspot.com

Div's class is divclass

In the above given code snippet i declare a css class .divclass and assign it to the div myDiv then using built-in attr() function of jquery i get the class name and display the class name in the span just after the div element. attr() function gets the value of an attribute for the first element in the set of matched elements.

So that's it. This is the way to get class name of any element in jquery.

I love your feedback.

Stay tune with nice-tutorials.blogspot.com

0 comments: