Moritz Moritz - 6 months ago 19
jQuery Question

Select element but not a certain child

My problem is:

I select a div with many children and would like to know how to not select a certain element which is actually a child of that previously selected element.

I already tried the :not(selectedElement) selector and the .not(selectedElement) selector or api (dont know how you call it...). Anyways, I also found someone who asked a similar question which didnt help so I guess the only way to find out what is wrong is to ask here if you have any approaches (I know stackoverflow is not meant to work like that but I seriously sat there many times and couldnt solve it):

HTML:

<div class="tablee" style="cursor:/*pointer*/;">
<table>
<tbody>
<tr>
<td>
<a href="something.php">
<img src="1.jpg">
</a>
</td>
<td class="postcontent">
<p class="postusername">
<a class="poster" href="something.php">momo</a>
<br>
some other text
</p>
</td>
<td>
<imgsrc="1.jpg">
</td>
</tr>
</tbody>
</table>
</div>


jQuery:

//non-dynamyic
$(".tablee").not($(this).find('a')).click(function() {
$(this).next().slideToggle();
});


So if tablee is clicked and not a link within it (within tablee element) the next element that comes after tablee shall toggle.

Answer

First of all, your selector if not selecting all the children and attaching the click event to then. The event is only on the actual selector and on click of a child the event is propagating up to the parent.

You have a click event on .tablee which you do not want to trigger on the click of any a within. In this case have a separate event on a with stopPropagation:-

$(".tablee").click(function() {
    $(this).next().slideToggle();
});

$(".tablee a").click(function(e) {
    e.stopPropagation();
});

This will then stop any click on a bubbling up to .tablee.

Comments