Recently whilst working on my day-job project I needed to get a HTMLElement from the DOM and then store it as a string. Using
innerHTML obviously didn’t make sense because it would only get the inner contents, not the outer. I wanted the whole element.
The logical choice was the lesser known property
outerHTML. I say lesser-known because you don’t really see it used all too much, in face of
innerHTML anyway. It isn’t the fact developers don’t know about it, it just doesn’t get used a whole lot.
<div id="myElement"><h1>This is my element with content</h1></div> <script> var el = document.getElementById('myElement'); var wholeEl = el.outerHTML; // <div id="myElement"><h1>This is my element with content</h1></div> </script>
As you can see using the
outerHTML property allows us to get an entire element and it gets returned as a string which we can store in a variable, transform or send off to a server. The more you know.