• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

How To Get An Entire HTMLElement As a String

Javascript · August 21, 2015

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.

The code

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

Dwayne

Leave a Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Thoughts on the Flipper Zero
  • I Joined Truth Social Using a VPN and Editing Some HTML to Bypass the Phone Verification
  • How To Install Eufy Security Cameras Without Drilling or Using Screws
  • How To Get The Hash of A File In Node.js
  • Wild Natural Deodorant Review
  • The Most Common iPhone Passcodes (and how to guess them)
  • Improving The Coopers Australian Pale Ale Extract Tin (and other tips)
  • NBN Box Installed Inside of Garage, Where Do You Put The Modem?
  • Neural DSP Reveal Details About the Long-Awaited Quad Cortex Desktop Editor
  • How To Paginate An Array In Javascript

Recent Comments

  • CJ on Microsoft Modern Wireless Headset Review
  • Dwayne on Microsoft Modern Wireless Headset Review
  • CJ on Microsoft Modern Wireless Headset Review
  • john on Microsoft Modern Wireless Headset Review
  • Dwayne on Why You Should Be Using globalThis Instead of Window In Your Javascript Code

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz