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.

share|improve this question
    
Are we talking about a single element? Or a nested DOM structure of arbitrary size? – nrabinowitz Jan 18 '12 at 18:01
    
Can you give an example output string that you'd expect? – David Thomas Jan 18 '12 at 18:02
7  
The storing of references to the event callbacks will not be reliable. – Alex Turpin Jan 18 '12 at 18:02
6  
How would you serialize the scope-chain for attached event handlers? This will get messy very quickly! – Yoshi Jan 18 '12 at 18:02
    
So much for REST. – Diodeus - James MacFarlane Jan 18 '12 at 18:14

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

share|improve this 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.

share|improve this 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;
    }
share|improve this 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));
share|improve this answer
    
Does this do events too? – ThinkingStiff Jan 20 '12 at 4:30
    
Yes, I think so. At least if you document.write(myString), you'll see the whole thing "stringified". As I said before, I just didn't test a way to turn the string back as an object and see how it behaves. – emanuelpoletto Jan 20 '12 at 5:21

Does this makes any sense if using jQuery?

$(this).serialize() 

For example visit:

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

share|improve this answer
4  
No, despite its name, .serialize() does not serialize objects to text, but rather serializes form data into a string that can be passed to a server – LocalPCGuy Jan 20 '12 at 6:09
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 */
});
share|improve this answer
    
This assumes in-memory storage of the DOM element, right? It's not clear to me whether the OP wants to be able to come back in a new session and be able to deserialize a stored element - your approach wouldn't work for this scenario. – nrabinowitz Jan 18 '12 at 20:10
    
@nrabinowitz no approach would work for that scenario (without reason). – Raynos Jan 18 '12 at 21:08
    
Well, I agree that it would be difficult, and the event handlers might be impossible to replicate effectively (unless you were picking from a limited list of pre-defined handlers). But to say that it's not possible seems a bit excessive. – nrabinowitz Jan 18 '12 at 22:23
    
@nrabinowitz I meant to say "(within reason)", of course you can serialize a DOM node as html, that's easily, but you can't copy event handlers easily without infrastructure. – Raynos Jan 18 '12 at 22:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.