JS innerHTML

The innerHTML property in JavaScript is a versatile tool used to manipulate the HTML content of an element within a web page. It allows for dynamic changes to the content of an element, making it essential for creating interactive and responsive web applications.

Purpose: To get or set the HTML content within an element.

Usage: Useful for dynamically updating the content of elements like div, p, span, etc., without having to reload the page.

Key Points

Getting HTML: When used as a getter, innerHTML returns the HTML content inside the element.

Setting HTML: When used as a setter, innerHTML allows you to insert or replace HTML content inside the element.

Security: Be cautious with user-generated content to avoid Cross-Site Scripting (XSS) attacks.

Synyex:

To get the HTML content of an element:

var content = document.getElementById("elementId").innerHTML;

To set the HTML content of an element:

document.getElementById("elementId").innerHTML = "New HTML content";

Example:

<div id="contentArea">Way To Code</div>
<button onclick="changeContent()">Click me</button>

<script>
  function changeContent() {
    // Change the content of the div element
    document.getElementById("contentArea").innerHTML = "<p>This is a development company!</p>";
  }
</script>

Output:

Way To Code