Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .data() Not Updating DOM

Tags:

jquery

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?

like image 575
senfo Avatar asked Sep 07 '12 15:09

senfo


1 Answers

$('#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()

like image 160
Naftali Avatar answered Oct 21 '22 15:10

Naftali