getElementById and querySelectorThe DOM (Document Object Model) is a tree-like representation of an HTML document created by the browser. To make web pages interactive with JavaScript, the very first step is selecting the HTML elements you want to inspect, manipulate, or listen to.
document.getElementById('id')Selects a single unique element by its id attribute. Returns the element or null:
# when using getElementById()! Just pass the plain ID string: "main-title".document.getElementsByClassName('class')Returns an HTMLCollection (array-like, live list) of all matching elements:
querySelector & querySelectorAllModern web development uses CSS selectors with two standardized methods:
+-----------------------------------------------------------------------------+
| MODERN DOM SELECTOR METHODS |
+-----------------------------------------------------------------------------+
| document.querySelector("selector") |
| -> Returns the FIRST matching element found in document (or null) |
| |
| document.querySelectorAll("selector") |
| -> Returns a static NodeList of ALL matching elements |
+-----------------------------------------------------------------------------+document.querySelector("h1")#): document.querySelector("#main-title").): document.querySelector(".btn-primary")[...]): document.querySelector("input[type='email']")document.querySelector("nav ul > li.active a")querySelectorAll:querySelectorAll returns a NodeList which supports modern array methods like .forEach():
| Method | Syntax | Return Type | Supports Complex Selectors? |
|---|---|---|---|
getElementById | getElementById('nav') | Single Element | No (ID only, fastest) |
querySelector | querySelector('#nav') | Single Element (First) | Yes (Any CSS selector) |
querySelectorAll | querySelectorAll('.card') | Static NodeList | Yes (Any CSS selector) |
document.getElementById("submit-btn") return if no element has that ID?document.querySelector(".active") differ from document.querySelectorAll(".active")?document.querySelector?document.querySelector?.forEach() on the result of document.querySelectorAll()?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Random Numbers Example | Changing Content and Style |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.