check if a clicked element has a class

Viewed 4041

I tried to check if a clicked element has a class, to decide what I need to do. For me the following code won't work. I tried a lot of variations which all failed.

$(window).click(function(e) {
  //console.log(e);
  //if ($(e).is('.lookingfor'))
  //if ($(this).is('.lookingfor'))
  if ($(e).hasClass('lookingfor')) {
    alert('matched');
  } else {
    alert('wrong class');
  }
});
1 Answers

e is the event which was raised. You instead need a reference to the element which was clicked, which can be retrieved from the target property of the event:

$(window).click(function(e) {
  if ($(e.target).hasClass('lookingfor')) {
    console.log('matched');
  } else {
    console.log('wrong class');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p class="lookingfor">This has the class</p>
<p class="foo">This does not</p>

Related