jQuery – get the last class of an element

By | May 27, 2021

In some cases, we need to get the last class of an element so that, we can write our logic based on that. Today, we will see, how we can do the same using jQuery code.

The jQuery Code:

var div_selector = $('#parent_div').attr('class');
var last_class = div_selector.substr( div_selector.lastIndexOf(' ') + 1);

And here is the full example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery - get the last class of an element</title>
  <style>
	#parent_div{width: 300px;border: 15px solid green;padding: 50px;margin: 20px; text-align:center;}
  </style>
</head>
<body>
	<div id="parent_div" class="abc container inner_div">
	<input type="button" id="click_button" value="Submit" />
	</div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#click_button').click(function(e){
var div_selector = $('#parent_div').attr('class');
var last_class = div_selector.substr( div_selector.lastIndexOf(' ') + 1);
alert(last_class);
});
});	
</script>
</body>
</html>

Hope, it will help you.