Musa Muaz
Musa Muaz

Reputation: 714

Checking if an element has a specific class in jquery not works

I am stopped up with a very simple functionality that worked with me many times back but not working right now.No specific errors in console also.

I am trying to check if there is a specific class for a div containing .form-content.inactive classes.I am trying to find if there is another class opened .

My codes are below mentioned

$(document).ready(function() {
  if($('.form-content.inactive').hasClass('opened')){
     $(".form-content a").click(function(event) {
        alert('has');
     });
  } 
});

No alerts are given on click.I am stupid now for a while :p

Upvotes: 3

Views: 1463

Answers (2)

BenG
BenG

Reputation: 15154

Instead of checking for opened you could use a delegate:-

$(document).ready(function() {

  $('body').on('click', '.form-content.inactive.opened a', function(event) {
    alert('has');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="form-content inactive opened">
  <a>Link</a>
</div>

This will fire the click event for a if the .form-content has both classes .inactive and .opened.

If you insist on using hasClass and you have multiple .form-content then you should use this to get the closest .form-content and check for both classes.

$(".form-content a").click(function(event) {

  var formContent = $(this).closest('.form-content');

  if(formContent.hasClass('inactive') && formContent.hasClass('opened')){
    alert('has');
  } 

});

Upvotes: 1

NiZa
NiZa

Reputation: 3926

If your div hasn't the class opened from the beginning, you should do it this way.

$(document).ready(function() {
     $(".form-content a").click(function(event) {
         if($('.form-content.inactive').hasClass('opened')){
            alert('has');
        } 
     });
});

Otherwise your code could work.. When your div has the class opened already before the document became ready, only then jQuery is able to subscribe your click element to the event.

$(document).ready(function() {
  if ($('.form-content.inactive').hasClass('opened')) {
    $(".form-content a").click(function(event) {
      alert('has');
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-content inactive opened">
  <a>Click!</a>
</div>

Upvotes: 3

Related Questions