innerHTML and outerHTMl in JS
Both innerHTML and outerHTML are properties of an HTML element that allow you to manipulate the DOM (Document Object Model) by getting or setting HTML content. However, they behave differently.
1. innerHTML
Definition: The innerHTML property allows you to get or set the HTML content inside an element.
Usage: It replaces only the content inside the element but does not modify the element itself.
<div id="demo">Hello, World!</div>
<script>
let element = document.getElementById("demo");
console.log(element.innerHTML); // Output: Hello, World!
element.innerHTML = "<b>New Content!</b>"; // Changes the inner content
</script>
Result:
<div id="demo"><b>New Content!</b></div>
2. outerHTML
Definition: The outerHTML property allows you to get or set the HTML of an element, including the element itself.
Usage: It replaces the entire element, not just its content.
<div id="demo">Hello, World!</div>
<script>
let element = document.getElementById("demo");
console.log(element.outerHTML); // Output: <div id="demo">Hello, World!</div>
element.outerHTML = "<p>Replaced with a paragraph!</p>"; // Replaces the whole div
</script>
Result:
<p>Replaced with a paragraph!</p>