I need to select parent div not child, how do I do this in jQuery.
Basically I want to create a simple login box, it should hide if and only if I click on parent div, if I click on child div the box should not hide.
Below is the code.
jQuery(document).ready(function ()
{
jQuery("li.login-link").click(function ()
{
jQuery("div#login-container").css("display", "block");
});
jQuery("div#login-container not:(div#login-box)").click(function ()
{
jQuery("div#login-container").css("display", "none");
});
});
<div id="login-container"> <!--parent div. Should hide when i click on this div-->
<div id="login-box"> <!--child div. Should not hide parent when i click on this-->
</div>
</div>
You can use .parent(): https://api.jquery.com/parent/
$('div#login-box').parent()
or
$('div#login-box').parent('div#login-container')
Edit
As per your comment below, I think you are after stop propagation: https://api.jquery.com/event.stoppropagation/
//hide the box when you click the parent:
$('div#login-container').click(function() { $(this).hide() });
// stop child click bubbling up to parent
$('div#login-box').click(function(e) {
e.stopPropagation();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With