jQuery Style How to - Check If an element has a certain class








Question

We would like to know how to check If an element has a certain class.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script type='text/javascript'>
$(window).load(function(){<!--  ww  w  . ja v a 2  s  .  c  o m-->
    if ( $('div').hasClass( 'test-class' ) ) {
        $( ".to-hide" ).css("display", "none");
    }
});
</script>
</head>
<body>
  <div class="test-class">This Stays</div>
  <div class="to-hide">THIS SHOULD BE HIDDEN</div>
</body>
</html>

The code above is rendered as follows:

Another example


<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from ww w . j a va2  s  .c om-->
              $("div").append($("p:first").hasClass("selected").toString());
        });
    </script>
  </head>
  <body>
    <body>
      <p>A</p>
      <div></div>
  </body>
</html>

The code above is rendered as follows:

hasClass(class) returns true if the specified class is present


<html>
  <head>
    <script type="text/javascript" src='http://code.jquery.com/jquery-1.5.2.js'></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--  w  w w . j  av  a 2 s. co  m-->
               $("p:last").addClass("selected highlight");
               console.log($("p:last").hasClass("selected").toString());
        });
    </script>
    <style>
      .selected { color:red; }
      .highlight { background:yellow; }
    </style>    
  </head>
  <body>
      <p>A</p>
      <p>B</p>
      <p>C</p>
    </body>
</html>

The code above is rendered as follows: