Javascript – How to get a HTML data value as a string with jQuery


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" ?

Best Solution


// Or old school

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);
  <li><a href="#" data-value="01">Test</a></li>

Thanks to @MaksymMelnyk for the heads up on dataset