Get the string representation of a DOM node

JavascriptStringDomCross BrowserElement

Javascript Problem Overview


Javascript: I have the DOM representation of a node (element or document) and I'm looking for the string representation of it. E.g.,

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

should yield:

get_string(el) == "<p>Test</p>";

I have the strong feeling, that I'm missing something trivially simple, but I just don't find a method that works in IE, FF, Safari and Opera. Therefore, outerHTML is no option.

Javascript Solutions


Solution 1 - Javascript

You can create a temporary parent node, and get the innerHTML content of it:

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

var tmp = document.createElement("div");
tmp.appendChild(el);
console.log(tmp.innerHTML); // <p>Test</p>

EDIT: Please see answer below about outerHTML. el.outerHTML should be all that is needed.

Solution 2 - Javascript

What you're looking for is 'outerHTML', but wee need a fallback coz it's not compatible with old browsers.

var getString = (function() {
  var DIV = document.createElement("div");

  if ('outerHTML' in DIV)
    return function(node) {
      return node.outerHTML;
    };

  return function(node) {
    var div = DIV.cloneNode();
    div.appendChild(node.cloneNode(true));
    return div.innerHTML;
  };

})();

// getString(el) == "<p>Test</p>"

You'll find my jQuery plugin here: https://stackoverflow.com/questions/2419749/get-selected-elements-outer-html/20079340#20079340

Solution 3 - Javascript

I dont think you need any complicated script for this. Just use

get_string=(el)=>el.outerHTML;

Solution 4 - Javascript

Under FF you can use the XMLSerializer object to serialize XML into a string. IE gives you an xml property of a node. So you can do the following:

function xml2string(node) {
   if (typeof(XMLSerializer) !== 'undefined') {
      var serializer = new XMLSerializer();
      return serializer.serializeToString(node);
   } else if (node.xml) {
      return node.xml;
   }
}

Solution 5 - Javascript

Use Element#outerHTML:

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

console.log(el.outerHTML);

It can also be used to write DOM elements. From Mozilla's documentation:

> The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.

https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML

Solution 6 - Javascript

Try

new XMLSerializer().serializeToString(element);

Solution 7 - Javascript

Use element.outerHTML to get full representation of element, including outer tags and attributes.

Solution 8 - Javascript

You can simply use outerHTML property over the element. It will return what you desire.

Let's create a function named get_string(element)

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

function get_string(element) {
 console.log(element.outerHTML);
}

get_string(el); // your desired output

enter image description here

Solution 9 - Javascript

If your element has parent

element.parentElement.innerHTML

Solution 10 - Javascript

I've found that for my use-cases I don't always want the entire outerHTML. Many nodes just have too many children to show.

Here's a function (minimally tested in Chrome):

/**
 * Stringifies a DOM node.
 * @param {Object} el - A DOM node.
 * @param {Number} truncate - How much to truncate innerHTML of element.
 * @returns {String} - A stringified node with attributes
 *                     retained.
 */
function stringifyEl(el, truncate) {
    var truncateLen = truncate || 50;
    var outerHTML = el.outerHTML;
    var ret = outerHTML;
	ret = ret.substring(0, truncateLen);
    
    // If we've truncated, add an elipsis.
    if (outerHTML.length > truncateLen) {
      ret += "...";
    }
    return ret;
}

https://gist.github.com/kahunacohen/467f5cc259b5d4a85eb201518dcb15ec

Solution 11 - Javascript

I have wasted a lot of time figuring out what is wrong when I iterate through DOMElements with the code in the accepted answer. This is what worked for me, otherwise every second element disappears from the document:

_getGpxString: function(node) {
		  clone = node.cloneNode(true);
		  var tmp = document.createElement("div");
		  tmp.appendChild(clone);
		  return tmp.innerHTML;
		},

Solution 12 - Javascript

if using react:

const html = ReactDOM.findDOMNode(document.getElementsByTagName('html')[0]).outerHTML;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBoldewynView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptgtournieView Answer on Stackoverflow
Solution 3 - JavascriptShishir AroraView Answer on Stackoverflow
Solution 4 - JavascriptBryan KyleView Answer on Stackoverflow
Solution 5 - JavascriptRich ApodacaView Answer on Stackoverflow
Solution 6 - JavascriptAlex PopaView Answer on Stackoverflow
Solution 7 - JavascriptPavel V.View Answer on Stackoverflow
Solution 8 - JavascriptSatish Chandra GuptaView Answer on Stackoverflow
Solution 9 - JavascriptVincnetasView Answer on Stackoverflow
Solution 10 - JavascriptAaronView Answer on Stackoverflow
Solution 11 - JavascriptbalaganView Answer on Stackoverflow
Solution 12 - JavascriptvictorkurauchiView Answer on Stackoverflow