jQuery exclude specific TD on click event?

Viewed 2173

How to exclude a specific TD (like the first one) from the row event of jQuery that I created below?

jQuery("#list tbody tr").click(function(){
alert('click this');
//some code here
});

jQuery("#list tbody tr td.exclude").click(function(){
alert('click not that');
//some code here
});
td { border: 1px solid black; padding: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="list">
    <tr>
        <td class="exclude">first</td>
        <td>second</td>
        <td>third</td>
    </tr>
    <tr>
        <td class="exclude">first</td>
        <td>second</td>
        <td>third</td>
    </tr>
</table>

I need to be able to have an event for my row but exclude from all TD with class exclude, is that possible?

6 Answers

You can exclude an element using not method:

$('#list tr td').not('.exclude').on('click', function(e) {
    console.warn('click!');
});

Try with :not() in the selector

jQuery("#list tbody tr td:not(.exclude)").click(function(){
alert('click this');
//some code here
});
td { border: 1px solid black; padding: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="list">
    <tr>
        <td class="exclude">first</td>
        <td>second</td>
        <td>third</td>
    </tr>
    <tr>
        <td class="exclude">first</td>
        <td>second</td>
        <td>third</td>
    </tr>
</table>

You could use target property on event object and check if it has class exclude.

$('tr').click(function(e) {
  if (!$(e.target)
    .parents()
    .andSelf()
    .hasClass('exclude')) {
    alert('Click')
  }
})
td {
  border: 1px solid black;
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="list">
  <tr>
    <td class="exclude"><div><span>first</span></div></td>
    <td>second</td>
    <td>third</td>
  </tr>
  <tr>
    <td class="exclude">first</td>
    <td>second</td>
    <td>third</td>
  </tr>
</table>

You can just use the :not selector in your jQuery so it would look something like this:

jQuery("#list tbody tr td:not(.exclude)").click(function(){
  alert('click this');
  //some code here
});

You can use the :not css selector just like that in one call:

jQuery("#list tbody tr td:not(.exclude)");

Try this you will get your goal...

$(document).ready(function(e) {
$('#list tr').click(function(e) {
  if (!$(e.target).hasClass('exclude')) {
    alert('Click')
  }
})

});

Related