Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 859
Andrew Avatar asked Jan 18 '12 17:01

Andrew


People also ask

How do you serialize a string in JavaScript?

In JavaScript, for example, you can serialize an object to a JSON string by calling the function JSON. stringify() . CSS values are serialized by calling the function CSSStyleDeclaration. getPropertyValue() .

How do I grab an element from a DOM?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

Can JavaScript modify DOM?

The DOM stands for Document Object Model. It can simply be understood as a tree of nodes created by the browser. Each of these nodes has its own properties and methods which can be manipulated using JavaScript. The ability to manipulate the DOM is one of the most unique and useful abilities of JavaScript.


1 Answers

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

like image 97
Nitin Jadhav Avatar answered Sep 18 '22 03:09

Nitin Jadhav