I tried to use the method data
(jQuery 1.7.1) in this code:
var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el);
and it does not work.
Note that this works:
var t = $(q).attr('data-message', message).insertAfter(el);
Why does the first variant not work?
EDIT: insertAfter
works correctly and new div is added after el
(which is instance of one element which I get by getElementById()
function; long story short I have a library that I extend).
When I say 'it does not work' I mean that the attribute 'data-message' is not stored.
Basically, . data() is for setting or checking the jQuery object's data value. If you are checking it and it doesn't already have one, it creates the value based on the data attribute that is in the DOM. . attr() is for setting or checking the DOM element's attribute value and will not touch the jQuery data value.
Creating an HTML Data Attribute We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using. For example, let's create a data attribute called "badges" and use it to attach a number to a p element.
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .
Using data
like that sets an arbitrary piece of data for this node; it doesn't add a new data-
attribute. Just add the attribute with the attr
function, and then access it with data
var q = $('<div class="form-error-marker"></div>').attr("data-message", message);
Now access it like this:
var message = q.data("message");
Here's a fiddle
When you use jQuery.data
you don't change element attributes, instead your data saved in $.cache
.
So if you want to change element attributes use jQuery.attr
, when you want to save some info use jQuery.data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With