Kostas
Kostas

Reputation: 53

jquery .html() function does not give data attribute set value

i have a piece of js code that takes the html code of an element in order to send it over for saving at the server side. The html itself is dynamically generated and the elements inside it have each a data-target attribute which is also set dynamically. So before sending the string of html to be saved the .html() of jquery is used like:

var SaveString = $('#ElementID').html();

the html I get, does not include the values of the data-target attribute of each child element and instead those appear blank

data-target=""

anyone could have a clue about what's going on there?

Upvotes: 2

Views: 122

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

This is because when you use the data() method to store information with an element it is stored in an object which jQuery uses internally as a cache. The information is not added to the DOM.

If you want to add the data-* attribute to the DOM, you would need to use attr() to set it, eg:

$element.attr('data-target', 'foo');

It will then be accessible when you retrieve the html() of a parent element.

Example fiddle

Upvotes: 3

Related Questions