Falytom logoFALYTOM
Games
ToolsUI ComponentsServicesProductsAbout
LoginSign Up
menu
  1. Home
  2. /Web Development
  3. /Javascript
  4. /Introduction To Dom
Your Progress0%
0 of 61 completed

JavaScript Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project

Introduction to the DOM

Understanding how JavaScript interacts with HTML

The Document Object Model (DOM) is the bridge between HTML and JavaScript. It's a programming interface that represents your web page as a tree structure of objects, allowing JavaScript to access and manipulate HTML elements, styles, and content dynamically. Understanding the DOM is essential for creating interactive web pages—from updating text to building complex single-page applications. Let's explore this fundamental web technology!

What Is the DOM?

The DOM (Document Object Model) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content.

Think of the DOM as:

  • A live representation of your HTML in memory
  • A tree structure where everything is a node
  • An API (interface) that JavaScript uses to interact with HTML
  • A bridge connecting HTML, CSS, and JavaScript

Why the DOM Matters

HTML
<!-- Static HTML (without JavaScript) -->
<div id="greeting">Hello!</div>
<button>Click Me</button>

<!-- This page just sits there, unchanging -->
<!-- User clicks button → Nothing happens -->
HTML
<!-- Dynamic HTML (with JavaScript + DOM) -->
<div id="greeting">Hello!</div>
<button onclick="changeGreeting()">Click Me</button>

<script>
function changeGreeting() {
  // JavaScript uses the DOM to find and change the element
  let greeting = document.getElementById('greeting');
  greeting.textContent = 'Hello, World!';
  greeting.style.color = 'blue';
}
</script>

<!-- User clicks button → Text changes and turns blue! -->

Key Concept: The DOM is created by the browser when it loads an HTML page. JavaScript can then use the DOM to make the page interactive and dynamic.

The DOM Tree Structure

The DOM represents your HTML document as a tree of nodes. Each HTML element becomes a node in this tree.

Simple HTML Example

HTML
<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <h1>Welcome</h1>
    <p>This is a paragraph.</p>
    <div>
      <button>Click Me</button>
    </div>
  </body>
</html>

Visualized as a Tree

TEXT
Document
  └── html (root element)
      ├── head
      │   └── title
      │       └── "My Page" (text node)
      └── body
          ├── h1
          │   └── "Welcome" (text node)
          ├── p
          │   └── "This is a paragraph." (text node)
          └── div
              └── button
                  └── "Click Me" (text node)

Tree Terminology:

  • Root: The top element (usually <html>)
  • Parent: Element that contains other elements
  • Child: Element inside another element
  • Siblings: Elements at the same level
  • Descendants: All elements nested inside (children, grandchildren, etc.)
  • Ancestors: All parent elements above (parent, grandparent, etc.)

Types of Nodes

Everything in the DOM is a node, but there are different types of nodes.

HTML
<div id="container" class="box">
  Hello World
  <span>Text in span</span>
  <!-- This is a comment -->
</div>
TEXT
Node Types in above HTML:
1. Element Node: <div>, <span>
2. Text Node: "Hello World", "Text in span"
3. Attribute Node: id="container", class="box"
4. Comment Node: <!-- This is a comment -->

Node Types Explained

  1. Element Nodes: HTML tags like <div>, <p>, <button>
  2. Text Nodes: Actual text content inside elements
  3. Attribute Nodes: Attributes like id, class, src
  4. Comment Nodes: HTML comments <!-- -->
  5. Document Node: The entire document (root of tree)
JAVASCRIPT
// Accessing different node types
let container = document.getElementById('container');

console.log(container.nodeType);  // 1 (Element node)
console.log(container.nodeName);  // "DIV"

// First child is text node "Hello World"
let firstChild = container.firstChild;
console.log(firstChild.nodeType);  // 3 (Text node)
console.log(firstChild.nodeValue);  // "Hello World"

// Common node types (numbers)
// 1 = Element
// 3 = Text
// 8 = Comment
// 9 = Document

The Document Object

The document object is your entry point to the DOM. It represents the entire HTML page and provides methods to access elements.

Common Document Properties

JAVASCRIPT
// Access document properties
console.log(document.title);              // Page title
console.log(document.URL);                // Full URL
console.log(document.domain);             // Domain name

// Access main elements
console.log(document.documentElement);    // <html> element
console.log(document.head);               // <head> element
console.log(document.body);               // <body> element

// Get all elements of a type
console.log(document.links);              // All <a> elements
console.log(document.images);             // All <img> elements
console.log(document.forms);              // All <form> elements
console.log(document.scripts);            // All <script> elements

Document Methods (Preview)

JAVASCRIPT
// Find elements (covered in next lesson)
document.getElementById('myId');           // Find by ID
document.querySelector('.myClass');        // Find by CSS selector
document.querySelectorAll('p');            // Find all matching elements

// Create elements (covered later)
document.createElement('div');             // Create new element
document.createTextNode('Hello');          // Create text node

// Write to document (not recommended)
document.write('Hello World');             // Writes to page (avoid in modern code)

How JavaScript Interacts with the DOM

The Process

  1. Browser loads HTML → Creates DOM tree in memory
  2. JavaScript runs → Can access the DOM
  3. JavaScript manipulates DOM → Changes structure, content, or style
  4. Browser updates display → User sees changes
HTML
<!DOCTYPE html>
<html>
<head>
  <title>DOM Interaction</title>
</head>
<body>
  <h1 id="title">Original Title</h1>
  <p id="text">Original text</p>
  <button id="btn">Change Content</button>

  <script>
    // 1. Wait for DOM to load
    document.addEventListener('DOMContentLoaded', function() {
      
      // 2. Get references to elements
      let title = document.getElementById('title');
      let text = document.getElementById('text');
      let button = document.getElementById('btn');
      
      // 3. Add event listener to button
      button.addEventListener('click', function() {
        
        // 4. Modify DOM when button is clicked
        title.textContent = 'New Title!';
        title.style.color = 'blue';
        
        text.textContent = 'The content has been changed!';
        text.style.fontSize = '20px';
      });
    });
  </script>
</body>
</html>

Important: JavaScript must wait for the DOM to be fully loaded before trying to access elements. Use DOMContentLoaded event or place scripts at the end of the <body>.

The DOM API

The DOM API is a collection of properties and methods that JavaScript uses to interact with the DOM.

Categories of DOM Operations

1. Selection: Finding elements

JAVASCRIPT
document.getElementById('myId')
document.querySelector('.myClass')
document.querySelectorAll('p')

2. Manipulation: Changing content and style

JAVASCRIPT
element.textContent = 'New text'
element.innerHTML = '<strong>Bold</strong>'
element.style.color = 'red'
element.classList.add('active')

3. Creation: Making new elements

JAVASCRIPT
document.createElement('div')
element.appendChild(newElement)
element.remove()

4. Events: Responding to user actions

JAVASCRIPT
element.addEventListener('click', function() {
  console.log('Clicked!');
});

DOM vs HTML Source Code

DOM can be different from HTML source

HTML Source

<!-- HTML Source Code (static) -->
<!DOCTYPE html>
<html>
<body>
  <div id="container">
    <p>Hello</p>
  </div>
</body>
</html>

<!-- This is what you write -->
<!-- Saved in your .html file -->
<!-- Doesn't change on its own -->
Output:
Not run yet...

DOM (In Memory)

<!-- DOM (dynamic, in memory) -->
<!-- Browser creates DOM from HTML -->
<!-- JavaScript can modify the DOM -->

<script>
// Add new element to DOM
let div = document.getElementById('container');
let newPara = document.createElement('p');
newPara.textContent = 'World';
div.appendChild(newPara);

// DOM now has 2 paragraphs
// But HTML source still shows 1
</script>
Output:
Not run yet...

Key Difference: The HTML source code is what you write. The DOM is what the browser creates and maintains in memory. JavaScript changes the DOM, not the HTML file.

Practical Examples

Example 1: Simple DOM Inspection

HTML
<!DOCTYPE html>
<html>
<head>
  <title>DOM Inspection</title>
</head>
<body>
  <h1>My Website</h1>
  <div id="content">
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
  </div>

  <script>
    // Inspect document
    console.log('Title:', document.title);
    console.log('URL:', document.URL);
    
    // Access body
    console.log('Body element:', document.body);
    console.log('Body tag name:', document.body.tagName);
    
    // Count elements
    let paragraphs = document.getElementsByTagName('p');
    console.log('Number of paragraphs:', paragraphs.length);
    
    // Get specific element
    let content = document.getElementById('content');
    console.log('Content div:', content);
    console.log('Content children:', content.children.length);
    
    // Tree structure
    console.log('First child of body:', document.body.firstChild);
    console.log('Last child of body:', document.body.lastChild);
  </script>
</body>
</html>

Example 2: Understanding Parent-Child Relationships

HTML
<!DOCTYPE html>
<html>
<body>
  <div id="parent">
    <p id="child1">First child</p>
    <p id="child2">Second child</p>
    <p id="child3">Third child</p>
  </div>

  <script>
    let parent = document.getElementById('parent');
    let child2 = document.getElementById('child2');
    
    // Accessing children from parent
    console.log('Parent has children:', parent.children.length);
    console.log('First child:', parent.firstElementChild.textContent);
    console.log('Last child:', parent.lastElementChild.textContent);
    
    // Accessing parent from child
    console.log('Child2 parent:', child2.parentElement.id);
    
    // Accessing siblings
    console.log('Child2 previous sibling:', child2.previousElementSibling.id);
    console.log('Child2 next sibling:', child2.nextElementSibling.id);
    
    // Loop through children
    console.log('\nAll children:');
    for (let child of parent.children) {
      console.log('- ' + child.textContent);
    }
  </script>
</body>
</html>

DOM Fundamentals Visualization

Understanding DOM structure and concepts

Output:
Click "Run" to execute your code...
💡 Tip: Use console.log() to see your output in the console above.

Key Takeaways

  • The DOM is a tree-like representation of an HTML document
  • It's created by the browser when an HTML page loads
  • JavaScript uses the DOM API to interact with HTML
  • Everything in the DOM is a node (elements, text, comments, etc.)
  • The document object is the entry point to the DOM
  • HTML elements are organized in a parent-child hierarchy
  • DOM changes are in memory—they don't modify the HTML file
  • JavaScript must wait for DOM to load before accessing elements
  • The DOM enables dynamic, interactive web pages
  • Understanding the DOM is essential for web development

What's Next?

You now understand the fundamentals of the DOM—what it is, how it's structured, and how JavaScript interacts with it! This foundation is crucial for everything that follows in DOM manipulation.

In the next lesson, we'll explore Selecting Elements—learning how to find and access specific HTML elements using methods like getElementById(), querySelector(), and more. This is where you'll start actually manipulating web pages!

💪 Practice Challenge:

Before moving on, try creating:

  1. Open your browser's DevTools and inspect the DOM tree of any website
  2. Console log document.body and explore its properties
  3. Create an HTML file and use console.log() to inspect the document object
  4. Draw out the DOM tree structure of a simple HTML page
  5. Identify parent, child, and sibling relationships in a webpage

Test Your Understanding

Question 1 / 4

What is the DOM?

Score: 0 / 0

Learning the Document Object Model fundamentals! 🌳

Previous
Spread Operator and Object Cloning
Next
Selecting Elements (querySelector, getElementById)

Continue Learning JavaScript

Join 2,000+ developers mastering JavaScript DOM manipulation. New lessons weekly - 100% FREE.

You might also like

UI Components

Ready-made components for your projects

Developer Tools

Boost productivity with handy generators

HTML Game

Learn HTML concepts through interactive gameplay

Join Our Web Development Training Program

Master frontend & backend development with hands-on projects.

JavaScript Tutorials

0 of 61 completed

Your Progress0%

Topics

Getting Started

  • What is JavaScript?
  • JavaScript vs Other Languages
  • Setting Up Your JavaScript Environment
  • Developer Console and Debugging Basics

JavaScript Fundamentals

  • Variables (var, let, const)
  • Data Types and Type Checking
  • Comments and Code Organization
  • String Methods and Template Literals
  • Type Conversion and Coercion
  • Operators (Arithmetic, Comparison, Logical)

Control Flow

  • If/Else Statements
  • Switch Statements
  • Ternary Operator
  • Truthy and Falsy Values
  • Logical Operators and Short-Circuiting

Loops and Iteration

  • For Loops
  • While and Do-While Loops
  • For...of and For...in Loops
  • Break and Continue Statements

Functions

  • Function Declarations and Expressions
  • Arrow Functions
  • Function Parameters and Arguments
  • Return Statements and Values
  • Scope and Closures
  • Higher-Order Functions and Callbacks

Arrays

  • Array Basics and Creation
  • Array Methods: Adding and Removing Elements
  • Array Iteration Methods (forEach, map, filter)
  • Array Methods: find, some, every, reduce
  • Sorting, Reversing, and Array Transformation

Objects

  • Object Basics and Properties
  • Object Methods and 'this' Keyword
  • Object Destructuring
  • Object.keys, values, entries
  • Spread Operator and Object Cloning

DOM Manipulation

  • Introduction to the DOM
  • Selecting Elements (querySelector, getElementById)
  • Modifying Elements (textContent, innerHTML, style)
  • Creating and Removing Elements
  • Event Listeners and Event Handling
  • Event Object and Event Delegation

Asynchronous JavaScript

  • Understanding Asynchronous Code
  • setTimeout and setInterval
  • Callbacks and Callback Hell
  • Promises and Promise Chaining
  • Async/Await

Error Handling

  • Try, Catch, Finally
  • Throwing Custom Errors

Modern JavaScript Features

  • ES6+ Overview
  • Modules (import/export)
  • Optional Chaining and Nullish Coalescing
  • Rest and Spread Operators

Working with Data

  • JSON (Parse and Stringify)
  • Fetch API and HTTP Requests
  • Working with Local Storage

Advanced Concepts

  • Classes and Object-Oriented Programming
  • Array and Object Advanced Patterns
  • Regular Expressions Basics

Best Practices & Real-World Application

  • JavaScript Best Practices
  • Debugging Techniques and Tools
  • Building a Complete Interactive Project
Falytom logoFALYTOM

Learn technologies like HTML, CSS, JavaScript, React, NodeJS and more through interactive games, tutorials, components and free tools. Transform your businesses with AI chatbots, SEO-optimized websites, and professional development services.

© 2025 Tomilola Group
  • Facebook logo
  • Twitter logo
  • Instagram logo
  • LinkedIn logo
  • GitHub logo
  • YouTube logo