How to usedocument.getElementById( ) in JavaScript
This method is used when you want to update the content of an HTML element with a specific ID. This method is useful when you want to update some specific sections of a webpage.
Example: Below is an example of using document.getElementById( ) to show the name of the user.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < title >Printing User Name</ title > </ head > < body > <!-- Create an element with the id "output" for document.getElementById() method --> < div id = "output" > This is div 1 </ div > < div > This is div 2 </ div > < script > // We are using PROMPT to get // the name from the user let userName = prompt("Method 1: Please enter your name:"); // Using document.getElementById // to update an element // in the HTML document with the entered name document.getElementById("output"). innerHTML = "Your name is: " + userName; </ script > </ body > </ html > |
Output:
JavaScript Program to Print Your Own Name
We will learn how to use JavaScript methods to display your name.
There are several ways in which we can print the name of a user such as the alert( ) method, console.log( ) method, and document.write( ) method and document.getElementById( ) method. Each of these methods serves different purposes and can be used in different scenarios.