Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting array out of data attribute without jQuery

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?

like image 817
Doddle Avatar asked Oct 16 '25 19:10

Doddle


1 Answers

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>
like image 169
benvc Avatar answered Oct 18 '25 08:10

benvc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!