Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select class but not certain data attributes

I am trying to select a number of div elements of a certain class but not having certain data attributes. For example, I have 12 divs with data attributes from 1 to 12 and I want to select all of them except those with data attribute 1, 11 and 12. This is my (not working) code so far:

$('div.randomize_class [data-value!=1],[data-value!=11],[data-value!=12]');

The aim is to shuffle only the matched divs and eventually append the ones with attribute 1, 11 and 12 at the end. The shuffling function works nicely, it's only about selecting a subset of the select class.

So after shuffling, I want to select only those with data attributes 1, 11 and 12. I tried this:

$('.randomize_class [data-value=1],[data-value=11],[data-value=12]')

Would be glad for any help! Thank you very much.

like image 597
Mario Avatar asked Jan 12 '16 10:01

Mario


3 Answers

You should use .filter() in combination with attribute value selector.

to select only those with data attributes 1, 11 and 12

$('.randomize_class').filter('[data-value=1],[data-value=11],[data-value=12]')

to select all of them except those with data attribute 1, 11 and 12. :not() Selector or .not() function to exclude the elements

 $('.randomize_class').filter(':not([data-value=1]),:not([data-value=11]),:not([data-value=12])')

OR

$('div.randomize_class').not('[data-value=1],[data-value=11],[data-value=12]');
like image 55
Satpal Avatar answered Sep 30 '22 05:09

Satpal


You've said you both want to not select the data-value=1 (and 11 and 12), and also that you do want to.


For the not case, you can use :not:

$('div.randomize_class:not([data-value=1]):not([data-value=11]):not([data-value=12])');

...which has the advantage of also working in CSS (not that I think that really applies here), provided you only use simple selectors inside :not (as CSS defines :not only takes simple selectors; jQuery goes further).

Or its cousin .not (which the :not documentation suggests is usually a better option):

$('div.randomize_class').not('[data-value=1], [data-value=11], [data-value=12])');

For the option of selecting only the data-value=1 (and 11 and 12), you do it with a simple attribute selector series:

$('div.randomize_class[data-value=1], div.randomize_class[data-value=11], div.randomize_class[data-value=12])');
like image 22
T.J. Crowder Avatar answered Sep 30 '22 05:09

T.J. Crowder


You need to use .not() to exclude those items

$('div.randomize_class').not('[data-value!=1],[data-value!=11],[data-value!=12]');

Your selector .randomize_class [data-value=1],[data-value=11],[data-value=12] will fetch all elements under randomize_class with data-value=1 and all elements in the page with data-value=11 or data-value=12

like image 33
Arun P Johny Avatar answered Sep 30 '22 07:09

Arun P Johny