I have an element which I'd like to give a data attribute which contains a series of values, i.e., an Array. Then I'd like to be able to select it based on any of the values in that series. Something like this:
<div id="example" data-my-series='["foo", "bar"]'></div>
Then I was hoping to select it based on the fact that it has "foo" in it. I'm not really sure how I'd go about it, though. I know I'd do $('div[data-my-series="foo"]') if I wasn't taking this approach, but, obviously that's not the case. Any suggestions?
Edit: Also, how can I achieve the inverse of this? i.e., select an element which does not have "foo" in its data-my-series?
$( "[data-my-series*='foo']" )
Here ya go!
The simplest way is very similar to what you are doing, just use the Attribute Contains Selector instead of the equals selector: $('div[data-my-series*="foo"]')
You can see more about it here: http://api.jquery.com/attribute-contains-selector/
Edit:
To answer the comment below, you can layer selectors in jQuery so take a look at the ":not()" selector. The usage would be $('div:not([data-my-series*="foo"])').
Make sure you don't put the div inside the :not. Also you will probably want to add [data-my-series] outside the :not as well to make sure you only select divs that have that data attribute.
Final product:
$('div[data-my-series]:not([data-my-series*="foo"])')
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