MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Selecting Elements: getElementById, querySelector0%
Study Materials
JavaScript for BeginnersProgress 0%
1.1What is JavaScript?1.2How JavaScript Works in Browser1.3Setting up Environment: VSCode, Live Server
10.1Selecting Elements: getElementById, querySelector10.2Changing Content and Style10.3Handling Events: click, input, submit
HomeTutorialsJavaScript for BeginnersSelecting Elements: getElementById, querySelector
Changing Content and Style

Selecting Elements: getElementById, querySelector

Beginner12 min read•Updated: 2026-09-15•By Er. Sumit Kumar (MSK Institute)
Study Materials

Selecting Elements: getElementById and querySelector

The 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.


1. The DOM Tree Mental Model

1document (Root)
2└── <html>
3 ├── <head>
4 │ └── <title>
5 └── <body>
6 ├── <header>
7 │ └── <h1 id="main-title">
8 └── <main>
9 ├── <button class="btn btn-primary">
10 └── <p class="description">

2. Classic Selection Methods

A. document.getElementById('id')

Selects a single unique element by its id attribute. Returns the element or null:

1// HTML: <h1 id="main-title">Welcome</h1>
2const heading = document.getElementById("main-title");
3console.log(heading); // <h1>Welcome</h1>
Note
[!NOTE] Do not include # when using getElementById()! Just pass the plain ID string: "main-title".

B. document.getElementsByClassName('class')

Returns an HTMLCollection (array-like, live list) of all matching elements:

1// HTML: <p class="text">One</p> <p class="text">Two</p>
2const paragraphs = document.getElementsByClassName("text");

3. Modern Selection Methods: querySelector & querySelectorAll

Modern web development uses CSS selectors with two standardized methods:

Visual Architecture Blueprint
+-----------------------------------------------------------------------------+
|                      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                       |
+-----------------------------------------------------------------------------+

Supported CSS Selectors:

  • By Tag Name: document.querySelector("h1")
  • By ID (#): document.querySelector("#main-title")
  • By Class (.): document.querySelector(".btn-primary")
  • By Attribute ([...]): document.querySelector("input[type='email']")
  • Complex Hierarchical: document.querySelector("nav ul > li.active a")

Example: Selecting Multiple Elements with querySelectorAll:

querySelectorAll returns a NodeList which supports modern array methods like .forEach():

1const cards = document.querySelectorAll(".course-card");
2 
3cards.forEach((card, index) => {
4 console.log(`Card ${index}:`, card);
5});

4. Selection Best Practices Comparison

MethodSyntaxReturn TypeSupports Complex Selectors?
getElementByIdgetElementById('nav')Single ElementNo (ID only, fastest)
querySelectorquerySelector('#nav')Single Element (First)Yes (Any CSS selector)
querySelectorAllquerySelectorAll('.card')Static NodeListYes (Any CSS selector)

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What does document.getElementById("submit-btn") return if no element has that ID?
Question 2
How does document.querySelector(".active") differ from document.querySelectorAll(".active")?
Question 3
Which symbol must prefix a class name when selecting with document.querySelector?
Question 4
Which symbol prefixes an ID selector in document.querySelector?
Question 5
Can you directly call .forEach() on the result of document.querySelectorAll()?
Next Lesson

Changing Content and Style

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Random Numbers ExampleChanging Content and Style

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master JavaScript for Beginners with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext