How to get classname of selected element in jquery

/ / 0 Comments

jQuery get div element classname: Here in this article will explain how to get classname or Fetch classname of element i.e Div, UL, li or any other HTML tag. You can also check my previous post on Learn jQuery, where have explained how to add click event on dynamically added element, and how to preview image before upload on server.

Steps to get classname in jQuery

  • HTML markup add Div tag, Li tag with some classname.
  • jQuery Code: Using attr() method

HTML Markup: 

Here we add div tags, and UL Li tags with some class.

 <div id="content" class="foo boo">
  Click Me
</div>

<ul id="ulItem" class="myUlClass">
 <li class='liItem'>One</li>
 <li class='liItem'>Two</li>
 <li class='liItem'>Three</li>
 <li class='liItem'>Four</li>
</ul>
<button id="btnShow">Get Class Name</button>

jQuery: Code to get classname on click 

 $("#content").on('click',function(){
  var getClassName=$(this).attr("class");
  alert(getClassName);
});


$("#ulItem li").on('click',function(){
  var getClassName=$(this).attr("class");
  alert(getClassName);
});

Conclusion: Here using .attr() we able to fetch classname of Div tag as well as Li tag in jQuery.

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to do a favor, then Buy me a coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

0 Comments