Reputation: 4059
How do you select a container while omitting some elements in it?
I am trying to make an html table's cells clickable, but the div in these cell must not follow the click event. These divs may have links. I set the selector as below and everything within the cell is clickable.
$('table').on('click', 'tr td', function(){
alert('clicked');
})
Now, I change the selector to not include div inside the element td, but this does not work: no part of the cell responds to any click.
$('table').on('click', 'tr td :not(div)', function(){
alert('clicked');
})
Here is the fiddle: https://jsfiddle.net/fo1eL8tb/
How do I make the cells clickable but not the div in the cells. If possible, I want to avoid stop propagation because the divs in the cells can have other event listeners.
EDIT
HERE is an example of what I am want. A div within the parent is left out of the click event.
Upvotes: 1
Views: 668
Reputation: 3040
Try to do this when click on the div return false
$('table').on('click', 'tr td :not(div)', function() {
alert('clicked');
});
$('table tr td div').on('click', function() {
return false;
});
Upvotes: -1
Reputation: 337580
How do you select a container while omitting some elements in it?
That's not possible. The DOM is a tree structure. If you select one node, then by proxy you are selecting all its child nodes too.
That being said you can achieve what you require by checking exactly what element caused the event handler to run, and then performing the required logic. Try this:
$('table').on('click', 'tr td', function(e) {
if (!$(e.target).is('td'))
return false;
console.log('clicked');
})
table {
width: 100%;
border-collapse: collapse;
}
td {
border: 1px solid #dddddd;
text-align: left;
padding: 10px;
min-height: 200px;
}
td div {
padding: 10px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>Tes</td>
<td>
<div>this is inside a <a href="foo.html">div</a></div>
Not inside div
</td>
<td></td>
<td></td>
</tr>
</table>
As you can see from this example, the console.log()
will only be called when the click event is not fired from the div
element within the td
.
Upvotes: 2