I want to work with an array to pass through using data-attribute. In my HTML-tag I've this attribute:
data-toshow='["tblp"]'
I can access and use it with jQuery when using
$().data('toshow')
But when using dataset.toshow
I don't get the same result. I actually don't get an array.
Can someone explain this to me? And give me the answer how to do the same without the use of jQuery?
jQuery's .data()
method automatically tries to convert the string in your custom data attribute to whatever type it appears to be (in this case an array). JavaScript just treats it as a string, so you need to parse the string to get the same array output you get with jQuery. For example:
// jQuery approach
const jqtest = $('div').data('toshow');
console.log(jqtest);
// Plain JavaScript approach
const jstest = JSON.parse(document.querySelector('div').dataset.toshow);
console.log(jstest);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-toshow='["tblp"]'></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With