How to convert a JavaScript DOM element (and its entire structure) to a string (without jQuery)? .. and re-display it on the page as text?

I am currently trying to grab a DOM element (and all its subelements) and store it as a string so that I can re-display it as plain text on a page. As below:

// Get DOM Element
var x = document.getElementById("para1");

// Create a new DOM Element and display x as text on the page
var div = document.createElement('div');
div.textContent = x;
document.body.appendChild(div); 

I expected to get something like <ul><li>One</li><li>Two</li><li>Three</li></ul>; however, I got it instead [object HTMLUListElement].

Here's the fiddle: http://output.jsbin.com/wesosu/1

+4
source share
1 answer

Use x.outerHTMLto get HTML content, including the element itself

var div = document.createElement('div');
div.textContent = x.outerHTML; // x.innerHTML instead if you only want the contents
document.body.appendChild(div); 
+6
source

All Articles