Reputation: 19358
For some reason, the not()
in the on()
function is not working. I only want the function to run if the aqua section
(parent) element is clicked, and do nothing if the gray div
(child) element is clicked.
jQuery:
$('body').append('<section><div class="someClass"></div><section>');
$('body').on('click', 'section:not(".someClass")', function(){
alert('Aqua not gray clicked.');
});
Also, why does the alert pop up twice if the section
aqua element is clicked?
Upvotes: 0
Views: 125
Reputation: 148110
There would be space between section and :not
for descendant selector and you probable need has with not, as the intended element is descendant of section. With space it will look sections not having class someclass
.
$('body').on('click', 'section :not(:has(.someClass))', function(){
alert('Aqua not gray clicked.');
});
You can bind event to section and by pass the execution of code in handler for section who have descendant with class someclass.
$('body').on('click', 'section', function(){
if($(this).find('.someClass').length > 0) return;
alert('Aqua not gray clicked.');
});
Upvotes: 1
Reputation: 887275
You need to check whether the actual element that was clicked (e.target
) has that class:
if ($(e.target).hasClass('someClass')) return;
Upvotes: 0