It seems jQuery 1.7.2 isn't updating the DOM data attributes for me. Given the following markup:
<ul id="foo">
<li data-my-key="12345">ABCDEF</li>
</ul>
Running the JavaScript below, I get some results I'm not expecting:
$('#foo li:first').data('my-key') // Returns 12345 - Expected
$('#foo li[data-my-key="12345"]') // Returns the expected <li>
$('#foo li:first').data('my-key', '54321')
$('#foo li:first').data('my-key') // Returns 54321 - Expected
$('#foo li[data-my-key="54321"]') // Returns an empty array - Not expected
Upon further investigation, I noticed the DOM has not been modified after setting a new value using the .data() function (verified with "Inspect Element" in Chrome 21.0.1180.81, Firebug 1.10.3 and Firefox 14.0.1).
The behavior is unexpected from my prospective, but is this the intended way for jQuery data to function? If so, what is the appropriate way to update data-* attributes with jQuery? Simply use the attr() function?
$('#foo li[data-my-key="54321"]')
is a attribute selector.
Using .data(..)
changes the elements properties which you cannot select from without using a filter.
If you want to get all the elements with a certain property you can do this (using filter(...)
):
$('#foo li').filter(function(index) {
return $(this).data('my-key') === 54321;
}); //returns all `#foo li` with data[my-key] === 54321
See here for more info: .prop() vs .attr()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With