[javascript] Get the string representation of a DOM node

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.

This question is related to javascript string dom cross-browser element

The answer is


Try

new XMLSerializer().serializeToString(element);

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


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


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

get_string=(el)=>el.outerHTML;

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;
        },

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: Get selected element's outer HTML


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


If your element has parent

element.parentElement.innerHTML

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

Let's create a function named get_string(element)

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

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

get_string(el); // your desired output
_x000D_
_x000D_
_x000D_ enter image description here


if using react:

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

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;
   }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to cross-browser

Show datalist labels but submit the actual value Stupid error: Failed to load resource: net::ERR_CACHE_MISS Click to call html How to Detect Browser Back Button event - Cross Browser How can I make window.showmodaldialog work in chrome 37? Cross-browser custom styling for file upload button Flexbox and Internet Explorer 11 (display:flex in <html>?) browser sessionStorage. share between tabs? How to know whether refresh button or browser back button is clicked in Firefox CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

Examples related to element

How can I loop through enum values for display in radio buttons? How to count items in JSON data Access multiple elements of list knowing their index Getting Index of an item in an arraylist; Octave/Matlab: Adding new elements to a vector add item in array list of android GetElementByID - Multiple IDs Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? Check if one list contains element from the other How to get the focused element with jQuery?