Select all elements inside a div but not a particular one

Viewed 120

How can I select all elements inside .content but not .bts? Here is my code. I'm using the not() function to exclude .bts but it's not working. What should be done?

$('.content').not('.bts').click(function() {
  alert("hit");
});
.content {
  height: 100%;
  width: 100%;
}

p {}

.bts {
  background: blue;
  height: 100px;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <p>test</p>
  <div class="bts">bts</div>
</div>

4 Answers

You can use $('.content *:not(.bts)')

.content * means that it will take all elements on .content, adding not(.bts) removes all elements with the bts class from the rule.

Demo

$('.content *:not(.bts)').click(function() {
  console.log("hit");
});
.content {
  height: 100%;
  width: 100%;
}

p {}

.bts {
  background: blue;
  height: 100px;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <p>test</p>
  <div class="bts">bts</div>
</div>

The .content is not a .bts, so .not won't do anything - rather, pass another selector to the click handler, to avoid triggering the handler when the .bts is clicked:

$('.content').on('click', ':not(.bts)', () => {
  console.log("hit");
});
.content {
  height: 100%;
  width: 100%;
}

p {}

.bts {
  background: blue;
  height: 100px;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <p>test</p>
  <div class="bts">bts</div>
</div>

This is how you can achieve it in Vanilla JS

let elements = document.querySelectorAll(".content >:not(.bts)");
elements.forEach(ele => {
  ele.addEventListener("click", function() {
    alert("hit")
  })

})
.content {
  height: 100%;
  width: 100%;
}

p {}

.bts {
  background: blue;
  height: 100px;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <p>test</p>
  <div class="bts">bts</div>
</div>

Since this answer hasn't been posted and is the simplest way to solve OP's issue according to his code, I'll do it : you just forgot to select .content children, you can do it with .children() function right after your .content selector like so :

$('.content').children().not('.bts').click(function() {
  alert("hit");
});
.content {
  height: 100%;
  width: 100%;
}

p {}

.bts {
  background: blue;
  height: 100px;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <p>test</p>
  <div class="bts">bts</div>
</div>

Related