1

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.

3
  • 1
    jquery's .data doesn't actually add DOM data attributes but rather keeps the attributes in JS land. Commented Nov 16, 2014 at 10:37
  • oh and how do I associate a dom's data attribute to be kept in the JS land ? while I am generating the dom element? Commented Nov 16, 2014 at 10:39
  • Honestly I would stay away from data attributes - if you're generating them you can push them into an array of objects and keep data related to them outside of your presentation layer. You can use .attr if you must: $("<div ... />").attr("data-foo", "bar") Commented Nov 16, 2014 at 10:45

2 Answers 2

1

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/

Sign up to request clarification or add additional context in comments.

1 Comment

In this case you add data attribute after as the element is located in DOM. This is not 'on the fly'.
1
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.