0

I was wondering if there's a way to select an item (div,span,whatever..) using javascript with jQuery (+ jQuery UI lib) based on its data attribute value. For example, let's say I have:

<div class="b">Hi</div>

I then assign some data to it:

$('.b').data('myKey', 1234);

Then, I want to find a div (or multiple divs that) satisfy condition myKey = 1234 . For example, like this:

var resultingElement = $('.b:data(myKey=1234)');

Is it possible by default, or do I have to implement this kind of selector myself? And no, I don't want to use HTML5's visible data-* attributes for this.

benas123798
  • 75
  • 1
  • 2
  • 7
  • 1
    Does this solve your problem? http://stackoverflow.com/questions/4191386/jquery-how-to-find-an-element-based-on-a-data-attribute-value – Kobi Tate Oct 26 '12 at 21:38
  • 1
    Why do you want to select by jQuery's `.data()` *(which is not an attribute)*? It would be a terribly expensive operation compared to using an actual attribute. – I Hate Lazy Oct 26 '12 at 21:48

3 Answers3

3

You can create a custom pseudo-selector to make things easy: http://jsfiddle.net/g2xKB/1/.

$.expr.pseudos.data = $.expr.createPseudo(function(args) {
    var items = args.split(",");  // the arguments (key, value)

    $.each(items, function(i, item) {
        item = item.trim();
        var isString = /^['"]|['"]$/.test(item);
        item = item.replace(/^['"]|['"]$/g, "");  // remove quotes

        if(!isString) {
            item = +item;  // if no quotes, it's a number
        }

        items[i] = item;
    });

    return function(elem) {
        return $.data(elem, items[0]) === items[1];
    }
});

You can then use it as follows:

$(".b:data('myKey', 1234)").css("color", "red");
pimvdb
  • 151,816
  • 78
  • 307
  • 352
1

Try this

    $("div.b").filter(function() { 
          return $.data(this, "myKey") == 1234; 
    });
YogeshWaran
  • 2,291
  • 4
  • 24
  • 32
0
var resultingElement = $('.b[data-myKey=1234]');

I'm not sure 100% sure, but I think there was an issue with camel-case selectors in data attributes at some point.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • 1
    `.data()` does not change the actual `data-` attribute within the HTML, so it cannot be read in this way. See [this fiddle](http://jsfiddle.net/8e9UN/1/). – Cat Oct 26 '12 at 21:43