JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to select an HTML element by Id in JavaScript?

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>
  <title>JavaScript document.getElementById() Example</title>
  <input type="text" id="username" />
  <button id="btnSubmit">Submit</button>
  <script type="text/javascript" src="code.js"></script>

JavaScript code

let btn = document.getElementById('btnSubmit');

btn.addEventListener('click', ()=>{
  let username = document.getElementById('username');

Recommended Posts