read unobtrusive data using jQuery
-
13-07-2021 - |
Question
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?
Solution
The best way is to just get the element attribute
$('#deleteFile').attr('data');
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 like
<a id="deleteFile" href="" data-fileid="123">Delete file</a>
then you can use
$('#deleteFile').data('fileid');
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 via data()
, it will not be changed in the actual tag attribute meaning data()
and attr()
will return different results thereafter
OTHER TIPS
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.
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.
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/