Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find elements by one class, but exclude other using JQuery

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

like image 995
Giancarlo Ventura Avatar asked Jan 30 '17 20:01

Giancarlo Ventura


3 Answers

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

like image 196
Sushanth -- Avatar answered Nov 01 '22 06:11

Sushanth --


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>
like image 37
Ionut Avatar answered Nov 01 '22 04:11

Ionut


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');
like image 3
Chetan Avatar answered Nov 01 '22 05:11

Chetan