Step 1: Create the HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Element By ID Example</title>
</head>
<body>
<h1 id="header">Hello, World!</h1>
<button id="changeTextButton">Change Text</button>
<script src="script.js"></script>
</body>
</html>
Step 2: Create the JavaScript File
Create a file named script.js
and add the following JavaScript code to it:
// Get the element by its ID
var headerElement = document.getElementById('header');
var buttonElement = document.getElementById('changeTextButton');
// Function to change the text content of the header
function changeHeaderText() {
headerElement.textContent = 'Text Changed!';
}
// Add an event listener to the button
buttonElement.addEventListener('click', changeHeaderText);
Explanation
- Get the Element by ID:
document.getElementById('header')
retrieves the HTML element with the idheader
.document.getElementById('changeTextButton')
retrieves the HTML element with the idchangeTextButton
.
- Change the Text Content:
- The
changeHeaderText
function changes thetextContent
of theheaderElement
to ‘Text Changed!’.
- The
- Add Event Listener:
buttonElement.addEventListener('click', changeHeaderText)
adds an event listener to the button. When the button is clicked, thechangeHeaderText
function is called, changing the text of the header.
Summary
In this example, we demonstrated how to use JavaScript’s getElementById
method to access and manipulate an HTML element. The HTML file contains a header and a button, and the JavaScript file changes the text of the header when the button is clicked. This basic example can be expanded to include more complex functionality as needed.
Leave a Reply