The document.getElementById() method in JavaScript is used to access HTML elements with a specific id attribute. This method is very useful for manipulating or retrieving information from elements on a webpage.
The getElementById() method retrieves an HTML element based on the id attribute. This is often used to modify the content or attributes of an element, or to retrieve the element's current state.
var element = document.getElementById("elementId");
elementId: The id of the HTML element you want to access.
<form>
<label for="username">Username:</label>
<input type="text" id="username" value="Way To Code"> <br><br>
<button type="button" onclick="showUsername()">Show Username</button>
</form>
<p id="display"></p>
<script>
function showUsername() {
// Get the value of the input field using getElementById
var username = document.getElementById("username").value;
// Display the value in the paragraph element
document.getElementById("display").innerText = "The username is: " + username;
}
</script>