-1

I have this code (with jQuery 1.9.1):

var Clon = $('#mylabel');

then I would change data-attributes, but is not established when I check the value:

Clon.data('hello','1');

but this method return the value:

Clon.attr('data-hello','1');

what can be the problem?

carlituxman
  • 1,201
  • 12
  • 22
  • What do you mean it doesn't work ? I hope you're not checking the attribute in HTML afterwards... – Denys Séguret Jun 17 '13 at 11:37
  • Are you sure it's not `appendTo($("#mycont"));` with `#` – Adil Shaikh Jun 17 '13 at 11:39
  • I don't see the purpose of downvoting this - it clearly is a possible duplicate but the question stands. – OzrenTkalcecKrznaric Jun 17 '13 at 11:40
  • problem could be that you have the id="mylabel" twice (after the clone) and an Id is expected to be only once in dom – caramba Jun 17 '13 at 11:40
  • In my answer there is a working code. If you would like to see what's in your data you can use .data('mydataname') to inspect the data. Jquery doesnt maintain it in DOM but in-memory. If you are looking for something that's visible in DOM, go with attr() - you can inspect it in e.g. Chrome (f12). – OzrenTkalcecKrznaric Jun 17 '13 at 12:01
  • I don't see the purpose of downvoting votes... thanks! – carlituxman Jun 17 '13 at 13:14
  • @carlituxman I voted to close this as a duplicate myself, but I don't think that's a valid reason to downvote (question itself is legit), so +1 – dsgriffin Jun 17 '13 at 18:54

1 Answers1

3

I think you are confused about what .data() does:

.data(name,value) stores the information in an internal jQuery cache - you cannot see it in the DOM structure.

.attr(name,value) changes the DOM attribute of that element. So this you will be able to see in the HTML code if you inspect it.

Precastic
  • 3,742
  • 1
  • 24
  • 29
  • sure?, then if I do console.log($('#selector').data('name'), I don't understand then this purpose – carlituxman Jun 17 '13 at 12:02
  • @carlituxman .data() is used to store information that you don't need in the DOM, against an element that is in the DOM. Think of data() as a big array of variables that jQuery manages for you. You say "store/retrieve this for me against div#x" and jQuery does the rest. Have a look here http://api.jquery.com/jQuery.data/ for the detail & for "why" watch this great youtube vid from the creator of jQuery http://youtu.be/78cuwVtMe2Y – Precastic Jun 17 '13 at 12:18
  • 1
    thank goodness there are developers like you, not like others who only seek downvoting... – carlituxman Jun 17 '13 at 13:20