Ajey
Ajey

Reputation: 8202

jquery add data attribute while creating dynamic dom elements

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.

Upvotes: 1

Views: 11040

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

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/

Upvotes: 1

Ashish
Ashish

Reputation: 743

Updated the code and fiddle.

var div = $('#ajey');

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

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

      text += "</div>";


      div.html(text); 
div.find('.child').data('child', 'true'); //data-child attribute is added but will not show in DOM when user inspects element
console.log($('.child').data('child')); //you can see the value of data-child attribute in console to make it confirm that it is added.

Working fiddle - http://jsfiddle.net/Ashish_developer/v0qmbL5z/1/

Upvotes: 1

Related Questions