001 – Javascript – Get Element By ID

Step 1: Create the HTML

Step 2: Create the JavaScript File

Create a file named script.js and add the following JavaScript code to it:

Explanation

  1. Get the Element by ID:
    • document.getElementById('header') retrieves the HTML element with the id header.
    • document.getElementById('changeTextButton') retrieves the HTML element with the id changeTextButton.
  2. Change the Text Content:
    • The changeHeaderText function changes the textContent of the headerElement to ‘Text Changed!’.
  3. Add Event Listener:
    • buttonElement.addEventListener('click', changeHeaderText) adds an event listener to the button. When the button is clicked, the changeHeaderText 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

Your email address will not be published. Required fields are marked *