Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom data attribute for a new node in Jquery does not work

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.

like image 545
Martin Vseticka Avatar asked Dec 25 '11 19:12

Martin Vseticka


People also ask

How add data attribute in jQuery?

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.

How do you add a data attribute?

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.

How get data attribute value in jQuery?

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" ).

How do you check if data attribute exists in jQuery?

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 .


2 Answers

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

like image 90
Adam Rackis Avatar answered Sep 27 '22 01:09

Adam Rackis


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

like image 44
Andrey Nikishaev Avatar answered Sep 27 '22 01:09

Andrey Nikishaev