Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
You can use arrays and hashes in HTML5 data attributes. Use JSON.parse, and make sure you're using single quotes around the brackets and double quotes inside the brackets.
<!DOCTYPE html>
<html lang="en">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<div id="animals" data-animals='["cat", "dog", "bird"]'></div>
<div id="vehicles" data-vehicles='{"motorcycle":"Harley", "car":"Herbie", "steamshovel":"Mike"}'></div>
<script type="text/javascript" src=""></script>
<script type="text/javascript" charset="utf-8">
var a = JSON.parse($('#animals').attr('data-animals'))[0];
var v = JSON.parse($('#vehicles').attr('data-vehicles')).car;

This comment has been minimized.

Copy link

@funkatron82 funkatron82 commented Mar 26, 2015

You can use the jquery function data instead of parse and attr:

var a = $('#animals').data('data-animals');  //will patse JSON automagically 

This comment has been minimized.

Copy link

@Yoelx Yoelx commented Jan 29, 2019

You can indeed retrieve it via the jquery function data, but if you do, you need to lose the data- part of the data-attribute. So in the example:

var a = $('#animals').data('animals'); // not .data('data-animals')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment