I was wondering if it is possible to store multiple key/values inside a data-attr
like:
<a href="#" data-social="network:facebook; socialId:123456789" id="facebook">Facebook</a>
and then when using them in my script just pick at them like $('#facebook').data('social.socialId');
or something like that instead of having to break each of them up into their own attribute?
I was wondering if it is possible to store multiple key/values inside a data-attr
like:
<a href="#" data-social="network:facebook; socialId:123456789" id="facebook">Facebook</a>
and then when using them in my script just pick at them like $('#facebook').data('social.socialId');
or something like that instead of having to break each of them up into their own attribute?
4 Answers
Reset to default 13You don't need to restrict it either to only one data-*
attribute. You can always use as many as you need.
<a href="#" data-social-network="facebook" data-social-id="123456789" id="facebook">Facebook</a>
var socialId = $('#facebook').data('social-id');
But, if you still insist. It is possible to store a JSON string and parse it.
<a href='#' data-social='{ "network": "facebook", "socialId": 123456789 }' id='facebook'>Facebook</a>
var socialId = $('#facebook').data('social').socialId;
The JSON Object is automatically parsed by jQuery.
you could store data in JSON format in the attribute like
<div id="myElement" data-json='["value1", "value2", "value3"]'></div>
and then retrieve it like
var data = JSON.parse($('#myElement').attr('data-json'));
Store them as an object.
$('#facebook').data('social', { network: 'facebook', socialId: 12345679 });
You can use JSON and that's automatically parsed, I believe
<a href="#" data-social="{network:facebook; socialId:123456789}" id="facebook">Facebook</a>
Would make possibilities for
$('#facebook').data('social').socialId;