1

The jQuery attribute set does not agree with the attribute as set by native js and apparently they exist differently and simultaneously. Can anyone tell me what is going on?

$(document).ready(function() {
    document.getElementById('attributed').setAttribute('data-foo','mydiv2'); 

    $('#attributed').data('foo','mydiv4');   

    // jQuery thinks it's mydiv 4 
    alert($('#attributed').data('foo'));     

    // native thinks it's mydiv 2! 
    alert(document.getElementById('attributed').getAttribute('data-foo'));
});
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Oliver Williams
  • 5,966
  • 7
  • 36
  • 78

1 Answers1

0

jQuery's .data() only reads the actual attribute off the DOM element if there is nothing already set in its own .data() data structure for that element and that key. So, once you've set a value with jQuery's .data() for that key it will have a different value than the actual HTML attribute on the element.

This is done for a couple reasons. Earlier browsers had memory leak issues if javascript objects were associated directly with a DOM object (as a property). And, pure attributes can only be strings. jQuery's .data() doesn't have either of these issues.

jfriend00
  • 683,504
  • 96
  • 985
  • 979