Modifying the HTML Page using JavaScript
JavaScript allows you to dynamically change the content, attributes, and style of HTML elements on your webpage. Here's a step-by-step tutorial.
1. Changing Text Content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modify HTML with JavaScript</title>
</head>
<body>
<h1 id="myHeading">Hello, World!</h1>
<script>
// Accessing an element by its ID
var headingElement = document.getElementById('myHeading');
// Modifying the text content of the element
headingElement.textContent = 'Greetings, JavaScript!';
</script>
</body>
</html>
2. Changing HTML Structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modify HTML Structure</title>
</head>
<body>
<div id="myDiv">This is a div.</div>
<script>
// Accessing an element by its ID
var divElement = document.getElementById('myDiv');
// Creating a new paragraph element
var newParagraph = document.createElement('p');
newParagraph.textContent = 'This is a new paragraph.';
// Appending the new paragraph to the existing div
divElement.appendChild(newParagraph);
</script>
</body>
</html>
3. Changing Attributes:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Modify HTML Attributes</title>
</head>
<body>
<img id="myImage" src="original.jpg" alt="Original Image">
<script>
// Accessing an element by its ID
var imageElement = document.getElementById('myImage');
// Modifying the 'src' attribute of the image
imageElement.src = 'new-image.jpg';
// Modifying the 'alt' attribute of the image
imageElement.alt = 'New Image';
</script>
</body>
</html>
These examples demonstrate the basics of modifying the HTML page using JavaScript. As you become more familiar with these concepts, you can create dynamic and interactive web pages by manipulating the DOM with JavaScript.