How to get classname using Jquery

How to get classname using Jquery

By Yashwant Chavan, Views 9147, Date 26-Nov-2015

Sometimes we don't know which CSS class is applied to Html element. In this tutorial we will learn how to get the class name using Jquery. If element contain multiple classes it will return each class name.

tags jquery jquery-attr

Jquery attr('class')

Jquery .attr() function returns the class attribute value. After that we are going to split the return value and get the respected class names.

$("#id").attr('class');

Get class name using Jquery

<!DOCTYPE html>
<html>
   <head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
      <script>
         $(document).ready(function(){  
          $("#btn").click(function(){
           $("#demo").attr('class').split(' ').map(function(clssName){     
            $("#message").append(clssName +" ");
            alert(clssName)
           })
          });  
           });  
          
      </script>   
   </head>
   <style>
      div{  
      padding:10px;
      margin:10px; 
      height:100px;
      width:100px;   
      display:inline-block;
      background:#ff9900;    
      }
   </style>
   <body>
      <h1>Get Class Name Using Jquery</h1>
      <div class="red green blue" id="demo">red green blue</div>
      <p id="message"></p>
      <p><input type="button" value="Get Class Name" id="btn"></p>
   </body>
</html>

Output

How to get classname using Jquery
Yashwant

Yashwant

Hi there! I am founder of technicalkeeda.com and programming enthusiast. My skills includes Java,J2EE, Spring Framework, Nodejs, PHP and lot more. If you have any idea that you would want me to develop? Lets connect: yashwantchavan[at][gmail.com]