Skip to main content
JavaScript Basics
CHAPTER 15 Beginner

JavaScript DOM Basics

Updated: May 12, 2026
25 min read

# 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 document object.
  • Select HTML elements using getElementById().
  • Select HTML elements using getElementsByClassName() and getElementsByTagName().
  • Select single or multiple elements using modern querySelector() and querySelectorAll().
  • 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. 1. document.getElementById('idname')
  1. 2. document.getElementsByClassName('classname')
  1. 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. 1. document.querySelector('cssselector') - Returns the first element that matches.
  1. 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.

html
12345678
<!-- Example HTML -->
<h1 id="mainTitle">Original Title</h1>

<script>
// Example JavaScript
let titleElement = document.getElementById("mainTitle");
console.log(titleElement.innerHTML); // Output: Original Title
</script>

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.

html
12345678910
<!-- Example HTML -->
<p class="alert">Warning 1</p>
<p class="alert">Warning 2</p>

<script>
// Example JavaScript
let alerts = document.getElementsByClassName("alert");
console.log(alerts[0].innerHTML); // Output: Warning 1
console.log(alerts.length);       // Output: 2
</script>

Example 3: getElementsByTagName

Similar to classes, this returns an HTMLCollection of all tags of that type.

html
1234567891011
<!-- Example HTML -->
<ul>
    <li>Item A</li>
    <li>Item B</li>
</ul>

<script>
// Example JavaScript
let listItems = document.getElementsByTagName("li");
console.log(listItems[1].innerHTML); // Output: Item B
</script>

Example 4: querySelector with an ID

querySelector uses CSS syntax, so you MUST include the # symbol for IDs.

html
12345678
<!-- Example HTML -->
<p id="bio">Hello World</p>

<script>
// Example JavaScript
let bio = document.querySelector("#bio");
console.log(bio.innerHTML); // Output: Hello World
</script>

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.

html
123456789
<!-- Example HTML -->
<div class="box">Box 1</div>
<div class="box">Box 2</div>

<script>
// Example JavaScript
let firstBox = document.querySelector(".box");
console.log(firstBox.innerHTML); // Output: Box 1
</script>

Example 6: querySelector with Complex CSS

You can target elements precisely, just like writing advanced CSS.

html
1234567891011121314
<!-- Example HTML -->
<div class="container">
    <p>Outside P</p>
    <div class="inner">
        <p>Inside P</p>
    </div>
</div>

<script>
// Example JavaScript
// Selects the 'p' that is directly inside '.inner'
let target = document.querySelector(".inner p");
console.log(target.innerHTML); // Output: Inside P
</script>

Example 7: querySelectorAll

This returns a NodeList of ALL matching elements. You can loop through a NodeList just like an array!

html
1234567891011121314
<!-- Example HTML -->
<button class="btn">Btn 1</button>
<button class="btn">Btn 2</button>
<button class="btn">Btn 3</button>

<script>
// Example JavaScript
let allButtons = document.querySelectorAll(".btn");

// Loop through the NodeList
for (let i = 0; i < allButtons.length; i++) {
    console.log(allButtons[i].innerHTML);
}
</script>

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.

javascript
12345678
// Example JavaScript
let missingElement = document.getElementById("doesNotExist");

if (missingElement) {
    missingElement.innerHTML = "Updated!";
} else {
    console.log("Element not found on this page.");
}

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!

javascript
1234567891011
// Example JavaScript
// BAD: Queries the DOM 3 times
document.getElementById("myDiv").style.color = "red";
document.getElementById("myDiv").style.fontSize = "20px";
document.getElementById("myDiv").innerHTML = "Hello";

// GOOD: Queries the DOM 1 time
const myDiv = document.getElementById("myDiv");
myDiv.style.color = "red";
myDiv.style.fontSize = "20px";
myDiv.innerHTML = "Hello";

Example 10: Parent and Child Nodes

You can navigate the DOM tree directly without querying.

html
1234567891011121314
<!-- Example HTML -->
<ul id="menu">
    <li>Home</li>
    <li>About</li>
</ul>

<script>
// Example JavaScript
const menu = document.getElementById("menu");
// Access the parent (the body tag)
console.log(menu.parentElement.nodeName); // Output: BODY
// Access the children
console.log(menu.children.length); // Output: 2
</script>

---

7. Common Mistakes for Beginners

  1. 1. Forgetting the # or . in querySelector: Writing querySelector("mainTitle") instead of querySelector("#mainTitle"). It will look for a literal <mainTitle> tag, fail, and return null.
  1. 2. Trying to .innerHTML a NodeList: document.getElementsByClassName("alert").innerHTML = "Error" will fail! You cannot set innerHTML on a collection. You must specify the index: alerts[0].innerHTML = "Error".
  1. 3. Placing <script> in the <head> without defer: If the script runs before the HTML <body> parses, getElementById will return null because the element hasn't been built yet.

8. Best Practices

  • Prefer querySelector and querySelectorAll. They are much more flexible and powerful than the older methods.
  • Save your selected elements to const variables 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:

html
12345678910111213141516171819
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: Arial; text-align: center; padding-top: 50px; background: #fdfdfd;}
        #heroTitle { font-size: 40px; color: #333; transition: 0.3s;}
        button { padding: 15px 30px; font-size: 18px; cursor: pointer; background: #007bff; color: white; border: none; border-radius: 8px;}
    </style>
</head>
<body>

    <h1 id="heroTitle">Welcome to the Website</h1>
    <button onclick="changeTitle()">Inspire Me</button>

    <script src="dom.js"></script>
</body>
</html>

dom.js:

javascript
1234567891011121314151617181920212223
// Example JavaScript
const phrases = [
    "Learn to Code",
    "Build the Future",
    "Master JavaScript",
    "Think Outside the Box",
    "Design Beautiful UIs"
];

function changeTitle() {
    // 1. Select the element using querySelector
    const titleElement = document.querySelector("#heroTitle");
    
    // 2. Get a random phrase from the array
    let randomIndex = Math.floor(Math.random() * phrases.length);
    let newText = phrases[randomIndex];
    
    // 3. Update the DOM
    titleElement.innerHTML = newText;
    
    // Bonus: Change the color slightly to show it refreshed
    titleElement.style.color = "#" + Math.floor(Math.random()*16777215).toString(16);
}

10. Exercises

  1. 1. Create a <p id="demo">Test</p> in HTML. Write JS to select it using getElementById and console.log its contents.
  1. 2. Create three <div> elements with the class card. Use querySelectorAll to select them, and use console.log to print the .length of the resulting NodeList.
  1. 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.
  • document is the global object representing the page.
  • getElementById is the fastest way to get a unique element.
  • querySelector uses CSS syntax to get the first match.
  • querySelectorAll returns a list of all matches.

15. Next Chapter Recommendation

Now that we know how to *select* elements, it's time to learn how to completely rewrite them. In the next chapter, JavaScript DOM Manipulation, we will learn how to change styles on the fly, add classes, and even create brand new HTML elements out of thin air.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·