Is it possible to convert a DOM element to a string and back?

dom, element, function, javascript, string

Solution

Using standard JavaScript, with `e` as an element:

Converting to a string:

const html = e.outerHTML

Converting back to an element:

const temp = document.createElement('div') // Can be any element
temp.innerHTML = html
const e = temp.children[0]

With jQuery it is very easy, although I discourage its use in general.

Converting to string:

var s = e.outerHTML;

Converting back to an element:

var e = $(s)[0];

`$("<div></div>")` parses the HTML and returns a jQuery object. You can obtain a reference to the first element with `[0]`

Problem

I am getting any DOM element (document.body for instance) and I want to convert it to a String like so: ``` function convert(el){ //should return a String } alert(convert(document.body)); //should alert (String) "document.body" alert(document.getElementById('foo')); //should alert (String) "document.getElementById('foo')" ``` I also want to convert those strings back (if possible not using eval()). For example: ``` function convertBack(el){ //should return a node } convertBack('document.body').innerHTML = 'foo'; //should change the innerHTML of document.body to foo ``` This may seem useless to some of you, but this my approach for a workaround to target elements, that don't yet exist. I am not using any library. Thanks!

Original source