Phob1a Phob1a - 3 months ago 17
HTML Question

How to get innerHTML including data attributes

I'm using

document.body.innerHTML
to get a text version of the HTML so I can store it and reload it later using jQuery's
append
. It works fine but it isn't saving the
data-*
attributes that I'm storing in the HTML nodes. Is there a method that can get me a string of all the innerHTML including this data attributes?

Answer

Assuming you are using jQuery .data():

jQuery's .data() method is storing data in Javascript and not as HTML attributes. Only existing data-* attributes are pulled into that object. For more information check the docs.

To save the data as HTML data attributes use .attr(). Something like the following:

$('.el').attr('data-foo', 'bar');