Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select elements which contain specified item in an array data attribute

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?

like image 328
2rs2ts Avatar asked Jun 28 '26 16:06

2rs2ts


2 Answers

$( "[data-my-series*='foo']" )

Here ya go!

like image 88
benhowdle89 Avatar answered Jul 01 '26 04:07

benhowdle89


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

like image 34
devinallenaz Avatar answered Jul 01 '26 06:07

devinallenaz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!