• 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

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • How To Mock uuid In Jest
  • How to Copy Files Using the Copy Webpack Plugin (without copying the entire folder structure)
  • Which Neural DSP Archetype Plugins Should You Buy?
  • Smoke Detector Randomly Goes Off Early Hours of The Morning
  • Removing A Character From The Start/End of a String In Javascript
  • How To Install Eufy Security Cameras Without Drilling or Using Screws
  • How to Use Neural DSP Archetype Plugins With the Quad Cortex
  • NBN Box Installed Inside of Garage, Where Do You Put The Modem?

Recent Comments

  • Thebe on How to Remove the My Sites Menu From the WordPress Admin Bar
  • Maccas worker jn the 2000s on Dear McDonald’s: bring back the Warm Cookie Sundae, you cowards
  • Anamika Singh on Testing Event Listeners In Jest (Without Using A Library)
  • Stefan on A List of WordPress Gutenberg Core Blocks
  • pandammonium on A List of WordPress Gutenberg Core Blocks

Copyright © 2022 · Dwayne Charrington · Log in

wpDiscuz