1

I have html:

<div class="item" data-value="1">item</div>

And js:

$('.item[data-value="1"]').data('value', 2');

So, now I have .item with data-value="2", I want get it by jQuery:

$('.item[data-value="2"]')

It returns []

I know that the problem is in the fact, that jQuery changes data values not changing data-value attribute. I know, that the problem can be solved by using attr method instead of data.

But is there any way to get objects by data with data changed by data method?

imkost
  • 8,033
  • 7
  • 29
  • 47
  • where do u see the "fact" that the `data-value` doesnt get updated? – PlantTheIdea May 01 '13 at 21:19
  • 1
    @PlantTheIdea: http://stackoverflow.com/questions/16308608/jquery-data-and-attr-weird-behaviour – uross May 01 '13 at 21:23
  • 1
    The fact is that it *doesn't* update the `data-value` attribute, you can easily test this with some basic javascript. I've run into similar situations, if part of your code is reliant on the attribute value itself then changing it via `data()` won't work. You need to change it with `.attr('data-value', abc)` – nzifnab May 01 '13 at 21:26

3 Answers3

1

You can filter the elements using filter and data methods.

$('.item').filter(function() {
   return $(this).data('value') === '2';
});

http://jsfiddle.net/3dfX7/

Ram
  • 143,282
  • 16
  • 168
  • 197
1

Using function from this answer, you can just write:

$('.item:data(value==2)');
Community
  • 1
  • 1
uross
  • 431
  • 5
  • 12
  • It works with jQuery UI and the function from this answer http://stackoverflow.com/a/2895933/1185123. Thank you. The only thing I'm afraid of is perfomance – imkost May 01 '13 at 21:35
  • No problem, thank you for edit. I havent tested it yet, so I do not know about its performance. – uross May 01 '13 at 21:52
  • Frankly I don't like how jQuery's `data()` method silently changes the value but not the attribute (so that next time you call `data('value')` you get a different value than is seen with a CSS selector `[data-value=something]`. I still argue that Joe's answer is better so that the attribute itself changes as well. – nzifnab May 01 '13 at 22:36
0

You've closed the bracket false:

$('.item[data-value="2"]')

should work using

.attr('data-value', 2)

to update data value :)

ahmet2106
  • 4,957
  • 4
  • 27
  • 38
  • it works, but i've wrote about this method in my question: "I know, that the problem can be solved by using attr method instead of data." – imkost May 01 '13 at 22:08