50

I have a custom data-attribute set by default:

data-equipment="0"

If i change it with jquery using .data()

$(this).data("equipment", 10)

and then use the getAttribute()

this.getAttribute("data-equipment")

i get the old value (0) and not the new one (10). But if i use

$(this).data("equipment") i get the new value (10).

Is this supposed to work like this or am i missing something?

Thanks!

pedroto
  • 643
  • 1
  • 6
  • 9
  • 1
    The `.data()` doesn't truly support data attributes. It just grabs the value from the attribute then uses its own data storage to hold it without ever updating the attribute. I personally wouldn't use jQuery's `.data()` for this. –  Aug 07 '13 at 15:17
  • data- attributes are accessible using element.dataset which i beleive is not used by jQuery. – Virus721 Aug 07 '13 at 15:19

1 Answers1

45

.data() doesn't operate on data attributes but in internal jQuery cache. Initially if no cache record is found, the data is read from a corresponding data- attribute if one exists, but that is the end of their co-operation.

If it operated on attributes, it would be useless for its purpose because attribute values must be strings.

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • 1
    I think this is the main difference between `$(this).data("equipment")` and `$(this).attr("data-equipment")`. If you retrieve some data attribute with `$(this).data("equipment")` and change attribute value with `$(this).attr("data-equipment", "some value")`, then you cannot retrieve new value with `$(this).data("equipment")` due to the caching mechanism of jQuery. – MÇT Mar 29 '17 at 22:04