Olivier Pons
Olivier Pons

Reputation: 15778

jQuery: Filtering by data doesn't work

I've done a lot of images for a small game. In each image, I store an integer through a function using this advice here

Like this:

for (var idx=0; idx<jeu.length; idx++) {
    $('#jeu').append(
        $('<img />').data('idx', idx)
    );
}

Then I check I can retrieve it "by hand":

> $('img')[11]
<img src="imgs/bleu.gif" />
> $($('img')[11]).data()
Object {idx: 5}

Now if i try to retrieve the object through data filter it doesn't work:

> $('img[data-idx="Object {idx: 5}"]')
[]
> $('img[data-idx="idx: 5"]')
[]

What is the way to do it?

Upvotes: 0

Views: 248

Answers (2)

guest271314
guest271314

Reputation: 1

Try

$("body").data("idx", 5);

var filterdata = function(key, val) {
  return $.map($("*"), function(el, i) {
    return $.data(el, key) === val ? $.data(el) : null
  })[0]
};

console.dir(filterdata("idx", 5));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div></div>

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You are using the data api to set the value, which does not update the element attributes, in this case you can use .filter()

$('img').filter(function () {
    return $(this).data('idx') == 5
})

Another choice is to use attribute

('<img />').attr('data-idx', idx)

then

$('img[data-idx="5"]')

Upvotes: 1

Related Questions