2

I am trying to set a data attribute to a div which previously doesn't have any value.

<div></div>

with jQuery, the first method (data) doesn't do anything, however the attr method works correctly.

var div = $('div');
div.data('superhero_one','batman');
div.attr('data-superhero_two','spiderman');

http://jsfiddle.net/5bT8p/

Am I using incorrectly the data function?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Alvaro
  • 9,247
  • 8
  • 49
  • 76

4 Answers4

5

It does work !

The actual thing behind that is , you can't see actual attribute when you use .data() because jquery sets that internally. but .attr() adds an attribute to the element which you can inspect.

see this demo --> http://jsfiddle.net/5bT8p/1/

Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
3
$("div").data("superhero_two","spiderman");

is the right syntax. But when inspecting, I'm only seeing data-superhero_two="spiderman" (as intended). The attribute from .attr is set in the DOM, and the .data is set in the JQuery object only.

By the way, use the document ready function to ensure its execution at the right time:

$(document).ready(function() {
    $("div").data("superhero_two","spiderman");
});
Hannes Schneidermayer
  • 4,729
  • 2
  • 28
  • 32
1
$("div").data("superhero_two","spiderman");

I suggest you give .data() | jQuery API Documentation a read. You'll find plenty of examples there to set and get data attributes.

Here is an in use example of the same on jsfiddle : http://jsfiddle.net/yrshaikh/293nk/1/

Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • I gave it a read, and this doesn't do what it should. At least Chrome is not showing the div changed at all. Only using attr() – Alvaro Mar 21 '14 at 09:49
  • As others said, it works as jQuery object,but doesnt reflect it in the DOM. Thanks :) – Alvaro Mar 21 '14 at 09:58
1

Is working fine, because they have different behaviours, jQuery.data:

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

so your element will not have any html attribute set, but the key-value pair is stored inside the jQuery object reference.

In short the difference is $.data is used for storing information without any alteration on the DOM element, attr is used to manipulate attributes of an element.

Demo: http://jsfiddle.net/5bT8p/3/

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
  • Then I misunderstood how it works, I should use attr() to actually apply the data right? Thanks – Alvaro Mar 21 '14 at 09:52
  • It depends, if you want to manipulate DOM attribute use attr (I think is your case), if you want to store data use, data; added in the answer – Irvin Dominin Mar 21 '14 at 09:59