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
  • 66,513
  • 17
  • 101
  • 130
Backo
  • 18,291
  • 27
  • 103
  • 170
  • 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
  • 630,263
  • 148
  • 957
  • 1,375
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,722
  • 2
  • 27
  • 40
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
  • 66,513
  • 17
  • 101
  • 130