Mario
Mario

Reputation: 2621

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.

Upvotes: 7

Views: 6167

Answers (4)

Satpal
Satpal

Reputation: 133403

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]');

Upvotes: 9

Jobelle
Jobelle

Reputation: 2834

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074218

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])');

Upvotes: 6

Arun P Johny
Arun P Johny

Reputation: 388316

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

Upvotes: 1

Related Questions