JavaScript DOM Basics
# JavaScript DOM Basics
We have learned a lot about variables, loops, functions, and data types. But how do we actually connect all this invisible logic to the visible buttons, text, and images on a webpage?
The answer is the DOM (Document Object Model). In this chapter, we will learn how JavaScript talks to HTML.
1. Introduction
When a web page loads, the browser reads your HTML file and creates a tree-like structure of objects in its memory. This is the Document Object Model (DOM).
Because it is an "Object Model", JavaScript (which loves objects) can read it, change it, add to it, or delete from it. The DOM is the bridge between the structural HTML and the behavioral JavaScript.
2. Learning Objectives
By the end of this chapter, you will be able to:
- Understand what the DOM is and how the browser builds it.
-
Use the global
documentobject.
-
Select HTML elements using
getElementById().
-
Select HTML elements using
getElementsByClassName()andgetElementsByTagName().
-
Select single or multiple elements using modern
querySelector()andquerySelectorAll().
- Build a Dynamic Heading Changer mini-project.
3. The document Object
Every action you take on the DOM must start with the document object. It represents your entire web page. If you want to access any element in the HTML page, you always start with accessing the document object.
4. Selecting Elements (The Old Way)
Historically, JavaScript relied on three main methods to select elements:
-
1.
document.getElementById('idname')
-
2.
document.getElementsByClassName('classname')
-
3.
document.getElementsByTagName('tagname')
5. Selecting Elements (The Modern Way)
Modern developers almost exclusively use the querySelector methods because they allow you to select elements using standard CSS selectors (like .class, #id, or div > p).
-
1.
document.querySelector('cssselector')- Returns the first element that matches.
-
2.
document.querySelectorAll('css_selector')- Returns a NodeList (like an array) of ALL elements that match.
---
6. Real-world Examples & Code Snippets
Example 1: getElementById
This is the fastest and most common way to grab a single, unique element.
Example 2: getElementsByClassName
Because multiple elements can have the same class, this returns an HTMLCollection (which looks like an array). You must use an index [0] to interact with a specific one.
Example 3: getElementsByTagName
Similar to classes, this returns an HTMLCollection of all tags of that type.
Example 4: querySelector with an ID
querySelector uses CSS syntax, so you MUST include the # symbol for IDs.
Example 5: querySelector with a Class
Remember, this only returns the FIRST match it finds, even if 10 elements have the class! You MUST include the . symbol for classes.
Example 6: querySelector with Complex CSS
You can target elements precisely, just like writing advanced CSS.
Example 7: querySelectorAll
This returns a NodeList of ALL matching elements. You can loop through a NodeList just like an array!
Example 8: Checking if an element exists
If you try to select an element that isn't on the page, JavaScript returns null. It is a best practice to check if it exists before trying to manipulate it.
Example 9: Saving DOM Elements to Variables
Querying the DOM takes a tiny bit of processing power. If you need to manipulate the same element 5 times, save it to a const variable first!
Example 10: Parent and Child Nodes
You can navigate the DOM tree directly without querying.
---
7. Common Mistakes for Beginners
-
1.
Forgetting the
#or.inquerySelector: WritingquerySelector("mainTitle")instead ofquerySelector("#mainTitle"). It will look for a literal<mainTitle>tag, fail, and returnnull.
-
2.
Trying to
.innerHTMLa NodeList:document.getElementsByClassName("alert").innerHTML = "Error"will fail! You cannot set innerHTML on a collection. You must specify the index:alerts[0].innerHTML = "Error".
-
3.
Placing
<script>in the<head>withoutdefer: If the script runs before the HTML<body>parses,getElementByIdwill returnnullbecause the element hasn't been built yet.
8. Best Practices
-
Prefer
querySelectorandquerySelectorAll. They are much more flexible and powerful than the older methods.
-
Save your selected elements to
constvariables at the top of your functions. Prefixing DOM variables with a$(e.g.,const $titleElement = ...) is a popular convention to remind yourself it is an HTML element, not just a string.
9. Mini Project: Dynamic Heading Changer
Let's build a UI that allows the user to click a button to randomly change the text of the main heading using querySelector and Arrays.
HTML:
dom.js:
10. Exercises
-
1.
Create a
<p id="demo">Test</p>in HTML. Write JS to select it usinggetElementByIdandconsole.logits contents.
-
2.
Create three
<div>elements with the classcard. UsequerySelectorAllto select them, and useconsole.logto print the.lengthof the resulting NodeList.
-
3.
Why does
document.querySelector(".card")only return one element even if there are three on the page?
11. MCQs (Multiple Choice Questions)
Q1: What does DOM stand for? A) Data Object Model B) Document Object Model C) Display Output Management D) Digital Orientation Module *Answer: B*
Q2: Which method returns an HTMLCollection of multiple elements? A) getElementById B) querySelector C) getElementsByClassName D) getElementByTagName *Answer: C*
Q3: What symbol is required to select a class using querySelector?
A) #
B) *
C) $
D) .
*Answer: D*
12. Interview Questions
Q: What is the difference between a NodeList and an HTMLCollection?
*A: getElementsByClassName returns a live HTMLCollection (if an element is added to the DOM later, the collection updates automatically). querySelectorAll returns a static NodeList (it is a snapshot of the DOM at the exact moment it was called). Also, NodeLists have built-in forEach array methods, while HTMLCollections do not.*
Q: Explain how the browser parses HTML into the DOM. *A: The browser reads the raw HTML text bytes, converts them into characters, identifies the tags (Tokens), creates objects for each tag (Nodes), and links them together in a tree structure based on their nesting. This tree is the DOM.*
13. FAQs
Q: Is jQuery still necessary for selecting elements?
*A: Not anymore. jQuery ($(".class")) became massively popular because selecting elements in old JS was difficult. Modern JS (document.querySelectorAll(".class")) has essentially made jQuery obsolete for this purpose.*
14. Summary
- The DOM is the browser's internal tree of your HTML.
-
documentis the global object representing the page.
-
getElementByIdis the fastest way to get a unique element.
-
querySelectoruses CSS syntax to get the first match.
-
querySelectorAllreturns a list of all matches.