I have the following in my source HTML:
<li><a href="#" data-value="01">Test</a></li>
I want to get the value of the data attribute so I am using the following:
var abc = $(this).data('value');
This works okay BUT not if there is a leading zero. For example the above placed the value "1" into abc.
Is there a way that I can get it not to convert the "01" into "1" ?
data-value being a correct attribute of an <a> element. Wouldn't it be better to use the rel attribute - JakeJ 2012-04-04 16:48
this.dataset.value;
// Or old school
this.getAttribute('data-value');
const a = document.querySelector("a");
console.log('Using getAttribute, old school: ', a.getAttribute('data-value'));
console.log('Using dataset, conforms to data attributes: ', a.dataset.value);
<ul>
<li><a href="#" data-value="01">Test</a></li>
</ul>
Thanks to @MaksymMelnyk for the heads up on dataset
attr may be a better option, since getAttribute can be buggy across browsers in some edge cases, like when the attribute is one that is used by DOM, such as obj.disabled - Juan Mendes 2012-04-04 17:28
this.dataValue then :) I don't know of any bug around this - Florian Margaine 2012-04-04 17:33
this.dataset.value will have that value - Maksym Melnyk 2015-08-20 15:26
You can use the attr() operator of jQuery:
var abc = $(this).attr('data-value');
From the jQuery data() documentation, it appears that you have to use .attr() to prevent the automatic type conversion:
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. When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
So, not to duplicate other answers, but rather to reinforce, the way to access the attribute without doing type conversion is:
var abc = $(this).attr('data-value');
$(this).attr('data-value');
This will return the string value with the leading 0.
have you tried?:
$(this).attr('data-value');
or
$(this).attr('data-value').toString();
$.attr doesn't need toString, it already returns a string, even if it didn't, calling toString would not bring back the original string if it had already been converted to a number - Juan Mendes 2012-04-04 16:53
Try :
this.data('value');
I think this is best way to get data attribute value.