getElementById() method in JavaScript

by danielkwood

HTML

<html>
    <head>
        <title>getElementById() method</title>
        <script src="script.js"></script>
    </head>

    <body>
        <p>Enter your name below:</p>
        <input id="username" type="text">
        <button onclick="getUsername();">Save</button>
        <p id="result"></p>
    </body>
</html>

JavaScript

function getUsername(){
  // Get access to the paragraph element with the ID 'result'
  var result = document.getElementById('result');
  
  // Get the user-inputted value from the username textbox
  var username = document.getElementById('username').value;
  
  // Update the result text and change its colour
  result.innerHTML = "Welcome back, " + username;
  result.style.color = "green";
}