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!

1

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, changed to ~= and changed my data-group. Thanks!
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.