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.
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:
Try
What you're looking for is 'outerHTML', but wee need a fallback coz it's not compatible with old browsers.
You'll find my jQuery plugin here: Get selected element's outer HTML
Use Element#outerHTML:
It can also be used to write DOM elements. From Mozilla's documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
If your element has parent
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):
https://gist.github.com/kahunacohen/467f5cc259b5d4a85eb201518dcb15ec