Undefined Title

data- attribute and jQuery.data


I wrote down this memo for data-* attribute and jQuery.data because I got stuck when using them on implemetation of JUMLY.scan.

Here is a gist to check behavior of them.

Relation between data-* name and key of .data()

I’m wondering foo-bar is camel style like fooBar. Pyphenation-style like foo-bar is my favor, but I won’t use this style in jQuery.

Require valid JSON for data-*

I just remembered we use JSON string in data-*. At first, I wrote like this.

<div id='foo' data-foo="{like:'apple'}">...

Actually, it didn’t work well. I needed to write like this.

<div id='foo' data-foo='{"like":"apple"}'>...

It can be refered like this.


Additionally, when it’s not valid JSON, it becomes just a string.

typeof $(foo).data("foo")

data-* is used as initial values (?)

The value of data-* is evaluated and captured in a slot of jQuery object when the object is built once. I’m not sure of the detail though I’ve not read the code.

<div id='foo' data-foo='{"like":"apple"}'>...
$(foo).data("foo").like = 'orange';

If we edit a part of object, the value of data-foo is not affected. It keeps the initial value.