1

I searched the net a bit but did not find a solution for my problem. This is my selector:

jQuery('[data-group="' + a + '"]').show()

The a is a text like swimming or any word. In HTML it looks like this:

<div data-group="swimming">...</div>

So the above selector would show that div if a = swimming. Now lets say that the data-group contains the word simming, but its not the only one, like this:

<div data-group="swimming,driving,flying">...</div>

How can I still select that div with a selector if a = swimming? I hope you know what I mean :).

Thanks!

Arnie
  • 661
  • 9
  • 20
  • Potential duplicate of http://stackoverflow.com/questions/190253/jquery-selector-regular-expressions – pistou Oct 16 '15 at 12:13

2 Answers2

3

You could use the value contains selector:

jQuery('[data-group*="' + a + '"]').show();

But would match even swimming for a equals swim.

If that matters, then filter it using e.g:

jQuery('[data-group]').filter(function(){
    return this.dataset.group.split(',').indexOf(a) != -1
}).show();

And better if you can change your HTML markup too:

<div data-group="swimming driving flying">...</div>

Then you could use:

jQuery('[data-group~="' + a + '"]').show();
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

You can also use .filter()

jQuery('[data-group]').filter(function(){
    return $(this).data('group').split(',').indexOf(a) > -1; //Convert to an array an check whether elements exist in array

    //Using native code
    //return this.dataset.group.split(',').indexOf(a) > -1
}).show();

References: indexOf() and HTMLElement.dataset

Satpal
  • 132,252
  • 13
  • 159
  • 168