JavaScript: how to serialize a DOM element as a string to be used later?

This may seem like a strange request, and it is quite out of the ordinary, but it's a challenge that I'm trying to solve.

Let's say you have a DOM element, which is made up of HTML and some CSS being applied, and some JS event listeners. I would like to clone this element (and all CSS and JS being applied), serialize it as a string that I could save in a database to be added to the DOM in a future request.

I know jQuery has a few of these methods (like $.css() to get the computed styles) but how can I do all of these things and turn it into a string that I can save in a database?

Update: Here is an example element:

<div id="test_div" class="some_class">
    <p>With some content</p>
</div>

<style>
#test_div { width: 200px }
.some_class { background-color: #ccc }
</style>

<script>
$('#test_div').click(function(){
    $(this).css('background-color','#0f0');
});
</script>

...and maybe a sample serialization:

var elementString = $('#test_div').serializeThisElement();

which would result in a string that looks something like this:

<div id="test_div"
     class="some_class" 
     style="width:200px; background-color:#ccc" 
     onclick="javascript:this.style.backgroundColor='#0f0'">
    <p>With some content</p>
</div>

so I could send it as an AJAX request:

$.post('/save-this-element', { element: elementString } //...

The above is only an example. It would be ideal if the serialization could look very similar to the original example, but but as long as it renders the same as the original, I would be fine with that.

Answers:

Answer

XMLSerializer.serializeToString() can be used to convert DOM nodes to string.

 var s = new XMLSerializer();
 var d = document;
 var str = s.serializeToString(d);
 alert(str);

MDN Link

Answer
var elem = ...;
var clone = elem.cloneNode(true);
var uuid = get_uuid();
storedElements[uuid] = clone;
storeInDatabase(uuid);

/* some time later */

getFromDatabase(function (uuid) {
    var elem = storedElements[uuid];
    /* do stuff */
});
Answer

I've got a piece of code from an example of http://api.jquery.com/jQuery.extend/ that I think will help you to get a complete string of your object. I just didn't figure out how to turn it back to an object yet. Anyway, I think it's a beginning. Maybe someone else could complete this answer... or I myself do it later.

First of all, create a complete clone of your element:

var el = $('div').clone(true, true);

Then, the code from api.jquery.com:

var printObj = function(obj) {
    var arr = [];
    $.each(obj, function(key, val) {
        var next = key + ": ";
        next += $.isPlainObject(val) ? printObj(val) : val;
        arr.push( next );
    });
    return "{ " +  arr.join(", ") + " }";
};

Finally:

var myString = printObj($(el).get(0));
Answer

I think the easiest thing to use to recreate your HTML object would be a JSON object, so you'd need a function that would return a JSON object, which you could then stringify to store in a DB. Something like the following might point you in the right direction, but it obviously isn't working fully as is, would be pretty dependent on the DOM element and you would have to write the function to deserializeObject as well.

    // NOT TESTED OR WORKING PROPERLY, FOR EXAMPLE ONLY
    // htmlObject is a raw HTML DOM element
    function serializeObject (htmlObject) {
        var objectToStore = {
            htmlElement: htmlObject.toString(),
            id: htmlElement.id,
            attrs: getAttrs(htmlObject) },
            css: htmlElement.style.cssText
        }
        return objectToStore;
    }
    function getAttrs(htmlObject) { 
      var tmp = [], i; 
      for (i = 0, i<htmlObject.attributes.length; i++) { 
        tmp.push({htmlObject.attributes[i].nodeName: htmlObject.attributes[i].value}); 
      } 
      return tmp;
    }
Answer

See https://github.com/ZeeAgency/jquery.htmlize -- this approach seems to work well in my tests, though I'm going to have to hack it up a bit to get it to work in IE6.

Answer

Does this makes any sense if using jQuery?

$(this).serialize() 

For example visit:

http://api.jquery.com/serialize/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.