Peter Samyn
Peter Samyn

Reputation: 156

jQuery select all but one element

I have html like below and want to select everything except for the <a> element. The end goal is to have two clickable areas and each do different things. But I have had trouble isolating the larger area from the <a> element.

<td title="title1" class="class1"> <p class="pclass1">value1</p></td>
<td>
    <p class="someClass1" title="someTitle1">someValue1</p>
    <p class="someClass2" title="someTitle2">someValue2</p></td>
    <p class="someClass3" title="someTitle3">someValue3</p>
</td>

<td><p title="otherTitle1" class="otherClass1">otherValue1</p></td>
<td><p title="otherTitle2" class="otherClass2">otherValue2</p></td>
<td><p title="otherTitle3" class="otherClass3">otherValue3</p></td>
<td><p title="otherTitle4" class="otherClass4">otherValue4</p></td>
<td title="title2" class="class2"><a href="#" class="no-select">don't select me</a></td>

So is it possible to select all of the 'td's except for that 'a' in the last 'td'?

I've tried things like 'td:not(a)', 'td:not(.no-select)' with no success

Upvotes: 0

Views: 273

Answers (2)

jessegavin
jessegavin

Reputation: 75650

One way to do it is to check the classname of the target element on the event.

$("td").on("click", function(e) {

  if (e.target.className === 'no-select') {
    return;
  }

  // Now we can do something here because we know
  // the event wasn't triggered by a `no-select` element
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

The easiest way to do this would be to delegate the click handler to the common parent tr element and then detect which element raised the event and run the appropriate logic. Something like this:

$('tr').click(function(e) {
  if ($(e.target).is('.no-select')) {
    console.log('link clicked...');
  } else {
    console.log('row clicked...');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td title="title1" class="class1"><p class="pclass1">value1</p></td>
    <td>
      <p class="someClass1" title="someTitle1">someValue1</p>
      <p class="someClass2" title="someTitle2">someValue2</p>
    </td>
    <td><p class="someClass3" title="someTitle3">someValue3</p></td>
    <td><p title="otherTitle1" class="otherClass1">otherValue1</p></td>
    <td><p title="otherTitle2" class="otherClass2">otherValue2</p></td>
    <td><p title="otherTitle3" class="otherClass3">otherValue3</p></td>
    <td><p title="otherTitle4" class="otherClass4">otherValue4</p></td>
    <td title="title2" class="class2"><a href="#" class="no-select">don't select me</a></td>
  </tr>
</table>

Upvotes: 1

Related Questions