Search code examples
jquerychildren

How can I exclude child class from click event?


I want to exclude the class noclick from the click function:

$( ".click" ).on( "click", ":not(.noclick *)", function() {
  console.log( $( this ).text() );
});
.noclick{
  background-color:pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:100%">
  <tr class="click">
    <th>Click</th>
    <th>Click</th>
    <th class="noclick">Nothing should happen here</th>
  </tr>
</table>


Solution

  • Simply remove the asterisk from ":not(.noclick *)"

    This makes it so events on .noclick's descendants don't trigger the function, but doesn't prevent .noclick itself.

    $( ".click" ).on( "click", ":not(.noclick)", function() {
      console.log( $( this ).text() );
    });
    .noclick{
    background-color:pink;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <table style="width:100%">
      <tr class="click">
        <th>Click</th>
        <th>Click</th>
        <th class="noclick">Nothing should happen here</th>
      </tr>
    </table>