add data attributes

add random generated data attributes to any element in the DOM

by Oliver Kelso

HTML

<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>
<div>
</div>

JavaScript

function makeid() {
  var text = "";
  var possible = "abcdefghijklmnopqrstuvwxyz0123456789";

  for (var i = 0; i < 5; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

// add random data id
$("div").each(function(index) {
  $(this).attr('data-info', makeid());
});

// displaying id in div
$("div").each(function(index) {
  $(this).text($(this).data("info"));
});