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.
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 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
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);
Use element.outerHTML to get full representation of element, including outer tags and attributes.
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
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;
精彩评论