Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .data() not working?

Recently I was coding away, and I ran into a weird issue. I was attempting to assign a data attribute to a new element I had created (via jQuery), only to discover it wouldn't actually assign the attribute. See the link below for an example, the code is listed below:

http://jsfiddle.net/y95p100c/1/

Any idea why this is happening? I've never stumbled into this...

var div = $("<div />") $(div).data("foo", "bar") console.log($(div)[0].outerHTML) // prints <div></div> 
like image 605
user1143682 Avatar asked Sep 16 '14 18:09

user1143682


People also ask

What is data() in jQuery?

The data() is an inbuilt method in jQuery which is used to attach data or get data for the selected elements. Syntax: $(selector). data(para1); Parameter : It accepts an optional parameter “para1” which specifies the name of the data to retrieve for the selected element.

How get data attribute in jQuery?

Answer: Use the jQuery attr() Method You can simply use the jQuery attr() method to find the data-id attribute of an HTML element.

How get data attribute from Element?

Approach: First, select the element which is having data attributes. We can either use the dataset property to get access to the data attributes or use the . getAttribute() method to select them by specifically typing their names.


1 Answers

data doesn't set data-* attributes. It manages a data cache unrelated to data-* attributes. It initializes from data-* attributes if there are any present, but never writes to them. To write to an attribute, use attr.

Example: Updated Fiddle

var div = $("<div />") $(div).attr("data-foo", "bar") console.log($(div)[0].outerHTML) 

What you're seeing is just one of the many ways this can be surprising. Another is that if your markup is <div id="elm" data-foo="bar"></div> and at some point you use $("#elm").data("foo") to get the value (and it will indeed be "bar"), then you do $("#elm").data("foo", "update"), the attribute remains data-foo="bar" but the data managed by data now has foo equal to "update". But the rule above explains it: data never writes to data-* attrs.

like image 162
T.J. Crowder Avatar answered Sep 21 '22 16:09

T.J. Crowder