About Lesson
Writing into an HTML Element: Using innerHTML:
The innerHTML property is one of the most common ways to manipulate and display data within an existing HTML element. This method allows you to change the content of any HTML element (e.g., <div>, <p>, <span>, etc.) dynamically.
Example:
JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>innerHTML Example</title>
<script>
function displayMessage() {
document.getElementById("message").innerHTML = "Hello, World!";
}
</script>
</head>
<body>
<h1 id="message">Welcome</h1>
<button onclick="displayMessage()">Change Message</button>
</body>
</html>
- Usage: Ideal for updating parts of a webpage without reloading it.
- Consideration: Be cautious when using innerHTML with user input to avoid security risks like cross-site scripting (XSS).