admin管理员组

文章数量:1134756

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

Share Improve this question edited Apr 21, 2014 at 20:50 El Developer 3,3451 gold badge23 silver badges40 bronze badges asked Nov 17, 2009 at 18:26 BoldewynBoldewyn 82.7k45 gold badges159 silver badges214 bronze badges 4
  • 4 With presumably version 11 Firefox also supports outerHTML: bugzilla.mozilla.org/show_bug.cgi?id=92264 – Boldewyn Commented Dec 5, 2011 at 16:26
  • 2 For now, looks IE, FF, Safari, Chrome, Opera all support outerHTML, see developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML – wangf Commented Apr 22, 2015 at 7:30
  • 2 Yes, it has now (since 2009, that is) become a trivial task :) – Boldewyn Commented Apr 22, 2015 at 7:48
  • 1 Yea, definitely outerHTML – neaumusic Commented Jul 23, 2015 at 7:13
Add a comment  | 

13 Answers 13

Reset to default 168

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.

What you're looking for is 'outerHTML', but we need a fallback because 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

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

get_string=(el)=>el.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;
   }
}

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

Try

new XMLSerializer().serializeToString(element);

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

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

If your element has parent

element.parentElement.innerHTML

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

While outerHTML is usually the answer, for Attr and Text(Child classes of the Node interface), there are other properties:

(<Element>x).outerHTML
(<Text>x).data
(<Attr>x).value;

See https://developer.mozilla.org/en-US/docs/Web/API/Node for more types of Nodes such as DocumentFragment and Comment

if using react:

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

本文标签: javascriptGet the string representation of a DOM nodeStack Overflow