3

Using jquery data() to set data attribute of an element, like so:

HTML:

<div id="some-el" data-number="0"></div>

JQ:

$("#some-el").data("number",1);

As we know, data changes variable internally. So inside inspector you cannot actually see that new value is 1. But this aside, if I do clone on the element with new data value, jquery clones original dom element without current data value!!!

$("#some-el").clone();

Results in <div id="some-el" data-number="0"></div> both internally and visibly!

I was thinking I could avoid this problem by simply using attr("data-number",1);

Anyways, I wanted to ask you if this is correct behaviour of dat()? Is what I'm seeing expected? and WHY?

2 Answers2

6

I think clone can accept a boolean to indicate a Clone with data and events, so Clone(true) should work: http://api.jquery.com/clone/

Here's a fiddle that works: http://jsfiddle.net/2pdNL/

Céryl Wiltink
  • 1,879
  • 11
  • 13
  • I guess OP is referring [this](http://i.stack.imgur.com/J76vp.jpg) behavior. It is not shown in the dev tools. – Praveen Dec 17 '13 at 11:54
  • This will make life easier, didn't want to rewrite my js :) thanks! –  Dec 17 '13 at 12:59
  • Clone(true) didn't work with jquery-ui sortable! so I had to go with attr way. –  Dec 20 '13 at 11:08
5

.data() is not setting the value in DOM.

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery)

But here is a workaround, instead of using

$("#some-el").data("number",1);  

Interact directly to DOM like

$("#some-el").attr("data-number",1);

JSFiddle

Also check this answer

Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164
  • What did you say that I didn't have in my question? :) –  Dec 17 '13 at 12:43
  • Also note, that if you want to set js object as value for the "data-number" (in this case) attribute, you have to stringify it. – lyubeto Feb 03 '15 at 09:07