Document object provides document.getElementById() method that helps you to select an HTML element by its id.
let htmlelement = document.getElementById("id");
document.getElementById()
method accepts an id of the HTML element that you want to select. If the id passed to the method matches the id present in the DOM, it returns an element; otherwise, it returns null
.
It is important to note that id is case-sensitive, and no two HTML elements can have the same id.
HTML code
<!DOCTYPE html> <html> <head> <title>JavaScript document.getElementById() Example</title> </head> <body> <input type="text" id="username" /> <button id="btnSubmit">Submit</button> <script type="text/javascript" src="code.js"></script> </body> </html>
JavaScript code
let btn = document.getElementById('btnSubmit'); btn.addEventListener('click', ()=>{ let username = document.getElementById('username'); alert(username.value); });