Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

jquery - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...