admin管理员组

文章数量:1277344

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.

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.

Share Improve this question edited Jun 30, 2015 at 15:46 BoltClock 724k165 gold badges1.4k silver badges1.4k bronze badges asked Jun 23, 2015 at 19:46 NiralanaNiralana 1791 gold badge3 silver badges12 bronze badges 1
  • that would bind click events to every tag under body but one, surely you need to be more specific. – dandavis Commented Jun 23, 2015 at 19:51
Add a ment  | 

2 Answers 2

Reset to default 10

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./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>

本文标签: javascriptSelector not in jQuery not workingStack Overflow