Javascript – jquery add data attribute while creating dynamic dom elements

domhtmljavascriptjquery

How to add data attribute while creating custom dynamic dom elements

like –

var div = $('#ajey');

  var text = "<div class='parent'>parent div";

  text +="<div class='child' data-child='true'>how do I add .data value for this div during on the fly dom creation?</div>";

  text += "</div>";

  div.html(text);

Fiddle here – Demo

Here I have added data-child this works, but when someone inspect elements via developer tools this is visible.

Where as the if I add via jquery .data() the data is not visible in the developer console.

But I am not able to figure out how to add data via jquery when I am creating elements on the fly.

Best Solution

var div = $('#ajey');

var text = "<div class='parent'>parent div";
text +="<div class='child' data-child='true'>how do I add .data value for this div during on the fly dom creation?</div>";
text += "</div>";

var parent = $(text);

parent.attr("data-foo", "bar");
parent.find('.child').attr("data-foo", "bar");

div.html( parent );

OR

var parent = $(text);

parent.data("foo", "bar");
parent.find('.child').data("foo", "bar");

div.html( parent );

console.log($('.parent').data('foo'));
console.log($('.parent').find('.child').data('foo'));

DEMO: http://jsbin.com/necoqo/1/