Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop jQuery .data() from converting

Tags:

jquery

Is there a way to stop the .data() function from converting the data to another type?

For example, with the HTML <div data-code-name="007">Bond, James</div>

$("div").data("codeName") returns 7 instead of "007"

Example: http://jsfiddle.net/dMHS4/

Update: I just noticed in the fiddle that if you change to jQuery 1.8.2 it does not convert. http://jsfiddle.net/dMHS4/2/

Update: Has jQuery 1.8 changed how .data() returns the value?

like image 395
Homer Avatar asked Sep 27 '12 13:09

Homer


1 Answers

Use .attr() instead of .data():

$("div").attr("data-code-name")

http://jsfiddle.net/dMHS4/1/


Taken from the jQuery documentation:

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null) otherwise it is left as a string. To retrieve the value's attribute as a string without any attempt to convert it, use the attr() method

like image 163
Curtis Avatar answered Sep 20 '22 06:09

Curtis