JavaScriptDOM & Events

Introduction to DOM (Document Object Model)

Understand the JavaScript DOM, how web pages are represented as objects, and how JavaScript can access and manipulate HTML elements dynamically.

What is the DOM?Link to this section

The DOM (Document Object Model) is a programming interface that represents an HTML document as a tree of objects. It allows JavaScript to read, access, and modify the structure, content, and style of a web page. When a browser loads an HTML page, it converts the page into a DOM structure that JavaScript can interact with.

Why DOM is Important?Link to this section

The DOM makes web pages dynamic and interactive. Without the DOM, JavaScript would not be able to change content after the page loads. DOM is used to:
  • Update text and HTML dynamically
  • Change styles
  • Handle user interactions
  • Create interactive web applications
Almost all modern frontend development depends on DOM manipulation.

How the DOM WorksLink to this section

The DOM represents an HTML document as a tree structure where:
  • Each HTML tag is a node
  • Elements have parent-child relationships
  • The document starts at the document object
Example explanation: documenthtmlbody → elements like div, p, button

Accessing DOM Elements :Link to this section

JavaScript provides several methods to access HTML elements.

getElementById :

Used to select an element by its unique ID.

getElementsByClassName :

Selects all elements with a given class name.

note

This returns a collection, not a single element.

getElementsByTagName :

Selects elements based on tag name.

querySelector :

Selects the **first matching element** using CSS selectors.

querySelectorAll :

Selects **all matching elements** using CSS selectors.

tip

querySelector and querySelectorAll are the most commonly used DOM selectors in modern JavaScript.

Changing DOM Content :Link to this section

JavaScript can change text and HTML dynamically.

warning

Using innerHTML with user input can cause security risks like XSS.

Changing Styles Using DOM :Link to this section

JavaScript can modify CSS styles of elements.

Creating and Adding Elements :Link to this section

JavaScript allows creating new elements dynamically.

DOM in Real-World Applications :Link to this section

DOM manipulation is used for:
  • Updating UI without page reload
  • Form validation
  • Dynamic content loading
  • Interactive dashboards

tip

Understanding DOM is essential before learning frameworks like React or Angular.
Check Your Understanding
Question 1 of 4

What does DOM stand for?

Practice Challenges

medium
  • Select an element by ID and change its text.
  • Change the background color of a paragraph using JavaScrip
  • Create a button dynamically and add it to the page.
  • Select all list items and log their text.