HTML var
Created By: chatGPT
In HTML, a variable can be represented using the
<script>
tag where you can declare and manipulate variables using JavaScript. Here's how to create a simple variable in an HTML document.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML Variable Example</title>
</head>
<body>
<h1>Variable in HTML</h1>
<script>
// Declaring a variable
var message = 'Hello, World!';
// Displaying the variable content
document.write(message);
</script>
</body>
</html>
In this example, we declare a variable named message and assign it the value 'Hello, World!'. We then use
document.write()
to display the content of the variable on the web page. It's important to remember that HTML alone does not handle variables; JavaScript is needed.<script>
var count = 10;
var greeting = 'Welcome to the website!';
// Output variable values
console.log(count);
console.log(greeting);
</script>
You can also manipulate variables in response to user interactions. For example, you can use variables in event handlers to update content dynamically.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Handling Example</title>
</head>
<body>
<h1>Change the Message</h1>
<button onclick="changeMessage()">Click Me</button>
<p id="display"></p>
<script>
var message = 'Hello! Click the button!';
function changeMessage() {
message = 'You clicked the button!';
document.getElementById('display').innerText = message;
}
// Initial display
document.getElementById('display').innerText = message;
</script>
</body>
</html>