I have a body with ID body
and inside it a div with class nav-container
. I want to remove certain classes when users click on the #body
, but not .nav-container
(it's an overlay type of menu).
Tried below code
HTML:
<body id="body"><div class="nav-container"><a href="#" id="close-btn"> X </a><nav class="display"><ul><li><a href="#"> One </a></li><li><a href="#"> Two </a></li><li><a href="#"> Three </a></li></ul></nav></div></body>
jQuery
$('#body :not(.nav-container)').click(function() {$('.cover').removeClass('active-cover');$('.nav-container').removeClass('active');});
It does not seem to be working for me though.
Best Answer
It wont work as not
exclude the selected elements which pass the earlier css-selector criteria since .nav-container
is not part of list that is selected by #body
(wont be list in this case as its ID), so you wont be able to exclude that.So basically what you need is
$(document).on("click", "div:not('.nav-container')",function() {$('.cover').removeClass('active-cover');$('.nav-container').removeClass('active');});
the first element shouldn't be the parent, like #body, rather the element. for example div:not('example')
works for every div except example.
$("div:not(.nav-container)").click(function() {alert("nav-container was not clicked");});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body id="body"><div class="nav-container"><a href="#" id="close-btn"> X </a><nav class="display"><ul><li><a href="#"> One </a></li><li><a href="#"> Two </a></li><li><a href="#"> Three </a></li></ul></nav></div><br /><div>click here </div></body>