I have multiple elements with a class like
<li class="target-class exclude-class"></li>
<li class="target-class exclude-class"></li>
<li class="target-class"></li>
<li class="target-class"></li>
<li class="target-class"></li>
I would like to find elements with target-class only if they dont have exclude-class. I tried
var elements = $find('.target-class exclude-class:not');
But I get all the elements
You are not using the :not
selector correctly.
You can select the elements for this scenario either using the not method or the :not selector.
$('.target-class:not(.exclude-class)'); // :not selector
or
$('.target-class').not('.exclude-class'); // .not method
Check Fiddle
You can use .not()
method:
var elements = $('.target-class').not('.exclude-class');
console.log(elements.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="target-class exclude-class">1</li>
<li class="target-class exclude-class">2</li>
<li class="target-class">3</li>
<li class="target-class">4</li>
<li class="target-class">5</li>
Your query syntax is not correct. It should be as following:
var elements =$find('.target-class:not(.exclude-class'));
or
var elements =$find('.target-class').not('.exclude-class');
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