Edit Template
Edit Template

JavaScript outerHTML

The outerHTML property allows you to get or replace the entire HTML element, including its own opening and closing tags—not just its content.

Syntax

				
					element.outerHTML         // Get the full HTML (including the element itself)
element.outerHTML = "..." // Replace the element entirely

				
			

Example HTML

				
					<div id="myDiv">
  <p>This is a paragraph</p>
</div>

				
			

Example JavaScript

				
					let myDiv = document.getElementById("myDiv");
myDiv.outerHTML = `<section><p>Replaced by Learn With Arshyan</p></section>`;

				
			

This completely replaces the <div id="myDiv"> element with a new <section>.

Key Features

FeatureDescription
 Replaces full elementUnlike innerHTML, it replaces the element itself, not just its content.
 Accepts HTML stringYou can replace the element with new HTML code.
 Removes event handlersAll event listeners on the original element are lost.

Caution:

If you’re inserting user input with outerHTML, it can expose your page to cross-site scripting (XSS) attacks:

				
					element.outerHTML = `<script>alert("Hacked!")</script>`; // ❌ Dangerous

				
			

Always sanitize user input before using it in HTML.

Summary

  • outerHTML reads or replaces an entire element, including its tags.

  • Great for swapping out components or injecting new templates.

  • Use with caution—replacing elements removes all events and may open up security risks.

Scroll to Top