Check class is exist in jquery

You can check whether a particular class is exists or not on selected element. You have to use "hasClass()" method for this. However you can also do this by "is()" method. But the hasClass() method makes for more readable code, and internally hasClass() is more efficient.

var flag = $('div').hasClass('container');

hasClass(classname) and is(.classname)

The hasClass method returns true if the the selected element has class name that you have passed otherwise it will returns false.

If you use "is" method you have to pass class name with dot(.) In below example I have explain with both methods.

<!DOCTYPE html>
  <title>jQuery With Example</title>
  <script src="" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('.btnClick1').click(function () {
        if ($(this).closest('div').hasClass('container')) {
          alert("Calss found using hasClass method");

      $('.btnClick2').click(function () {
        if ($(this).closest('div').is('.container')) {
          alert("Calss found using is method");

  <div class="container">
    Click1 Button used hasClass method.<br /> Click2 Button used is method.<br />
    <button class="btnClick1">Click1</button>
    <button class="btnClick2">Click2</button>
Click1 Button used hasClass method.
Click2 Button used is method.

No comments :

Please Give Your Feedback