1

I am happy that the html5 data attribute exists.

I can write a simple string into html attributes and access them via jquery.

But .... wouldn't it be nice to have more than a simple string?

Is there no way to encode JSON into these data attributes.

In my current use case I need to store a list of strings in a html5 data attribute.

guettli
  • 25,042
  • 81
  • 346
  • 663

4 Answers4

1
   <div id ="test" data-something='{"something":"something"}'></div>

string in the data-attribute is automatically converted to a JavaScript object.

you can access this in javascript like this.

var somethingObject = $("#test").data("something");

var jsonSomethingObject = JSON.stringify(somethingObject);

console.log(somethingObject); //this will print the main javascript object
console.log(jsonSomethingObject);// this will print stringify javascript object

you can refer the snippet for same

var someObject = $("#test").data("student");
    
var jsonData = JSON.stringify(someObject);
 
 $('#display').text("id:"+someObject.id +" name:"+someObject.name)
console.log(someObject);
console.log(jsonData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" data-student='{"name": "Dhiraj", "id": 1}' />

<div id="display"></div>
Dhiraj
  • 1,430
  • 11
  • 21
0

You can put json as string in data attribute and use JSON.parse() to get it.

Lucas Franco
  • 383
  • 2
  • 13
0

Seems like you can use JSON.stringify

$("#ele").attr('data-example', JSON.stringify(new Array('1', '2')));

console.log($("#ele").attr('data-example'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='ele' data-example="nothing"></div>
Zze
  • 18,229
  • 13
  • 85
  • 118
0

You can store JSON strings in data- attributes.

function onPClick(evt) {
  var special = evt.target.getAttribute('data-special');
  if (special != null) {
    try {
      console.log("JSON", JSON.parse(special));
    } catch (error) {
      console.log("STANDARD", special);
    }
  } else {
    console.log("NULL");
  }
}
var ps = document.getElementsByTagName("p");
for (var pi = 0; pi < ps.length; pi++) {
  var p = ps[pi];
  p.onclick = onPClick;
}
<p>I am special!</p>
<p data-special='YES!'>I am special!</p>
<p data-special='{"a":"bob"}'>I am special!</p>

For separation of concerns, it would be prettier to hold you data in a place that doesn't have to update the HTML every time it changes:

var p = document.body.appendChild(document.createElement("p"));
p.innerHTML = "Click me!";
Object.defineProperty(p, 'mySuperSecretValue', {
  value: 37,
  writable: true,
  enumerable: true,
  configurable: true
});
p.onclick = function pclick(evt) {
  console.log(evt.target.mySuperSecretValue++, evt.target.outerHTML);
};
Emil S. Jørgensen
  • 6,216
  • 1
  • 15
  • 28