outerHTML
In this tutorial, you will learn about the outerHTML property in JavaScript.
The outerHTML property is a part of the JavaScript HTMLElement object and it allows developers to access and manipulate the HTML content of an element, including the element itself. The outerHTML property returns the content of an element, including the opening and closing tags, as a string of HTML.
Syntax
The syntax for accessing the outerHTML property is as follows:
element.outerHTML;Where element is a reference to the HTML element whose outerHTML property you want to access.
Example
Let's consider the following HTML code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>outerHTML Example</title>
</head>
<body>
<div id="example">
<p>Hello, World!</p>
</div>
<script src="script.js"></script>
</body>
</html>In the above code, we have a div element with an id of example and a p element with the text "Hello, World!".
Now, let's access the outerHTML property of the div element using JavaScript:
const element = document.getElementById("example");
console.log(element.outerHTML);The output of the above code will be:
<div id="example">
<p>Hello, World!</p>
</div>Modifying the outerHTML
You can also modify the outerHTML property to change the content of an element, including the element itself. For example, let's change the content of the div element to "Hello, JavaScript!" using the outerHTML property:
const element = document.getElementById("example");
element.outerHTML = "<div id='example'><p>Hello, JavaScript!</p></div>";In the above code, we are replacing the entire div element with a new div element containing the text "Hello, JavaScript!". The output of the above code will be:
<div id="example">
<p>Hello, JavaScript!</p>
</div>The outerHTML property is a powerful tool for manipulating the HTML content of an element, including the element itself. It allows developers to easily access and modify the HTML structure of a web page using JavaScript.
Conclusion
- The
outerHTMLproperty allows developers to access and manipulate the HTML content of an element, including the element itself. - The
outerHTMLproperty returns the content of an element, including the opening and closing tags, as a string of HTML. - The
outerHTMLproperty can be used to change the content of an element, including the element itself, by assigning a new HTML string to it. - The
outerHTMLproperty is a powerful tool for manipulating the HTML structure of a web page using JavaScript.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on