0

I am trying to use jQuery to build up some HTML, for which I would like to later get the HTML string. One of the things I am adding is some background data(), which I believe translates to the data-* attributes of the element. Here is an example:

var test = $("<div></div>");
test.data("foo", "bar");
var test2 = $("<div></div>");
test.text("blah");
test2.append(test);
console.log(test2.html());

Unfortunately, when I output the HTML to the log, I get this:

<div>blah</div>

but not the "foo" data. Is there an API call that will output the HTML for a jQuery object, including any data that has been set in it?

j08691
  • 204,283
  • 31
  • 260
  • 272
David Whiteman
  • 110
  • 1
  • 10

3 Answers3

2

Data will set a value on the object you have there - test in your example , not the rendered html. What I believe you are looking for is attr

See what I mean here -

var test = $("<div></div>");
test.attr("foo", "foo");
test.attr("bar", "bar");
var test2 = $("<div></div>");
test.text("blah");
test2.append(test);
console.log(test2.html());

In the console - this now reads like <div foo="foo" bar="bar">blah</div>;. Here it is in fiddle example - https://jsfiddle.net/wx38rz5L/3849/

You can change the first or second arguments to whatever you want. The first argument is the name, and the second argument is the value, so if you did :

test.attr('data-test', 'my value!'); 

You'd end up with

<div data-test="my value!">

You can read more about jquery attr here - http://api.jquery.com/attr/

ajmajmajma
  • 13,712
  • 24
  • 79
  • 133
0

This will do what you desire:

var test = $("<div></div>");
test.attr("data-foo", "bar");
var test2 = $("<div></div>");
test.text("blah");
test2.append(test);
console.log(test2[0].outerHTML);
n1ru4l
  • 488
  • 1
  • 10
  • 29
0

Using the .data() method doesn't create an actual data-info attribute. to set an attr use .attr()

var test = $("<div></div>");
    test.attr('data-foo', 'bar');
    var test2 = $("<div></div>");
    test.text("blah");
    test2.append(test);
    console.log(test2.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Aya Salama
  • 1,458
  • 13
  • 17