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?

Rajaprabhu Aravindasamy
  • 64,912
  • 15
  • 96
  • 124
Backo
  • 17,309
  • 27
  • 96
  • 165
  • 1
    No, parsing the content of attributes is out of the scope of [attribute selectors](http://api.jquery.com/category/selectors/attribute-selectors). You need to do that manually. – Bergi Jun 04 '14 at 06:28
  • @Bergi - If so, how can/should I improve the code and the related selector? – Backo Jun 04 '14 at 06:30
  • you can try using the `*=` operator like this `a[data-a*='"one"'][data-b] {...}` – King King Jun 04 '14 at 06: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"}'` – King King Jun 04 '14 at 06:35

3 Answers3

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.

Community
  • 1
  • 1
Bergi
  • 572,313
  • 128
  • 898
  • 1,281
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/

Fabricator
  • 12,556
  • 2
  • 25
  • 39
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(..)
Rajaprabhu Aravindasamy
  • 64,912
  • 15
  • 96
  • 124