Reputation: 2955
I'm building a concept jQuery Page Builder / Prototype. I'm using jQuery 3.x and am having some difficulty in selecting a child element of a parent element. I am using jQuery draggable & droppable, however these likely aren't the cause of my problems here and thus I will only show a snippet of the code, it's fairly straightforward:
html
<h2>Parent Element <span>Child Element / Could be anything</span></h2>
jQuery
$('#stage *').click(function() {
$('#stage *').removeClass('js__widget-selected');
$(this).addClass('js__widget-selected');
});
From the above code which I've written I'm essentially adding a class to the clicked element (the class added is purely for styling purposes to add a green border.)
The problem comes when I'm trying to click on any HTML markup/element child (the span
) within the parent element, in this case the <h2>
.
The child element could be anything.
Result I'm getting:
With this particular code, when I try to select the <span>
or whatever element it is, it's actually adding the class to the parent and not the child. I'm wondering whether it's something to do with the wildcard selector here?
Any guidance would be thankful! Many thanks!
Upvotes: 0
Views: 126
Reputation: 81016
When you click on a child, the click event happens first on the child and then on the parent and then its parent, etc. So that last ancestor with the same click event handler is going to be the one that appears selected. Here is a relevant reference for understanding the behavior: https://javascript.info/bubbling-and-capturing
You need to call event.stopPropagation()
(add event
as a parameter to your click handler function) after handling it to prevent it from bubbling up to the parent.
$('#stage *').click(function(event) {
$('#stage *').removeClass('js__widget-selected');
$(this).addClass('js__widget-selected');
event.stopPropagation();
});
.js__widget-selected {
border: green 2px solid
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="stage">
<h2>Parent Element <span>Child Element / Could be anything</span></h2>
</div>
Upvotes: 2