1

I am using jQuery and I have the following HTML code:

<a href="/link" data-a='{"one":"sample1","two":"sample2"}' data-b="true">Title</a>

I would like to find the above link by using multiple attribute selectors but for/with specific values contained in data-* attributes. That is, I can find the above link this way

selector = 'a[data-a][data-b]'
$(selector).bind(...)

but I would like to be more specific by finding links having data-a and data-b attributes and whose attribute data-a contains the one key.

How can I do that?

4
  • 1
    No, parsing the content of attributes is out of the scope of attribute selectors. You need to do that manually. Commented Jun 4, 2014 at 6:28
  • @Bergi - If so, how can/should I improve the code and the related selector? Commented Jun 4, 2014 at 6:30
  • you can try using the *= operator like this a[data-a*='"one"'][data-b] {...} Commented Jun 4, 2014 at 6:33
  • I'm afraid that the HTML code you edited is not a well-formed JSON string, it should be data-a='{"one":"sample1","two":"sample2"}' Commented Jun 4, 2014 at 6:35

3 Answers 3

1

Parsing the content of attributes is out of the scope of attribute selectors. You need to do that manually, by filtering the selected elements:

$('a[data-a][data-b]').filter(function() {
    try {
        return "one" in JSON.parse($(this).attr("data-a"));
    } catch(e) {
        return false;
    }
}).on(…)

You could of course implement a custom selector (or use a regex selector1), but that won't make much difference. And might dramatically decrease performance.

1: Uh, better not on JSON.

Sign up to request clarification or add additional context in comments.

Comments

0

This will work, but does not guarantee data-a is valid json lol

select = 'a[data-a*=\'"one":"\'][data-b]';

using the 'contains' selector: http://api.jquery.com/attribute-contains-selector/

Comments

0

we can .filter() the first set of collection to ensure whether the element's data-* attribute contains the particular key.

You can do like this,

$('a[data-a][data-b]').filter(function(){
 return 'key' in JSON.parse($(this).data('a'));
}).bind(..)

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.