- Home
- /
- JS outerHTML
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- JS outerHTML
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
This is a paragraph
Example JavaScript
let myDiv = document.getElementById("myDiv");
myDiv.outerHTML = `Replaced by Learn With Arshyan
`;
This completely replaces the <div id="myDiv">
element with a new <section>
.
Key Features
Feature | Description |
---|---|
Replaces full element | Unlike innerHTML , it replaces the element itself, not just its content. |
Accepts HTML string | You can replace the element with new HTML code. |
Removes event handlers | All 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 = ``; // ❌ 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.