I do not find any example how to read unobtrusive data using jQuery. For example below
<a id="deleteFile" href="" data="123">Delete file</a>
I would like to read data
attribute from a element. How to do that?
I do not find any example how to read unobtrusive data using jQuery. For example below
<a id="deleteFile" href="" data="123">Delete file</a>
I would like to read data
attribute from a element. How to do that?
It's better to define data attributes like this:
<a id="deleteFile" href="" data-id="123">Delete file</a>
Then you can read it:
var id = $('#deleteFile').data('id');
This is not really good idea to use attr
for such situations.
You should be using data-*
where *
is a key you would like to use:
<a id="deleteFile" href="" data-file-id="123">Delete file</a>
then you can read with:
$('#deleteFile').data('fileId');
Youll notice the property was converted from file-id
to fileId
this happens automatically to conform with the spec. It should also be noted that jquery will attempt to conver a value to its javascript native type. Meaning the value of that access will be a javascript Number
as opposed to s string. This can have implications if you have a leading 0
and becuase 01
would be converted to 1
. If you explicitly need the value as a string then use attr
:
$('#deleteFile').attr('data-file-id');
You should also note that when using attr
you give the full attribute name as-is instead of just the data property name in camelCase.
If you want to stick with your coding then you may try this
var a = $("#deleteFile").attr("data");
Heres a demo http://jsfiddle.net/Ht7Eg/3/
The best way is to just get the element attribute
If your using a newish jquery library version (higher than 1.6 i belive) you can also use HTML5 data attributes with jQuery's
data()
. Change your anchor link to something likethen you can use
However do NOT use them interchangeably, use one method only otherwise you may incur issues later on as jQuerys
data()
will only READ the data attributes then store them in an internal cache. If you change anything viadata()
, it will not be changed in the actual tag attribute meaningdata()
andattr()
will return different results thereafter