JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript DOM Document


The JavaScript DOM Document is the entry point to everything you do with the Document Object Model. When a web page loads in the browser, the browser creates a DOM tree that represents the HTML structure of that page. The document object represents the entire HTML document and allows JavaScript to access, modify, create, and remove elements dynamically. Almost every interaction with a web page using JavaScript starts with the document object.

In this tutorial, you will learn what the JavaScript DOM document is, how it works, commonly used document methods and properties, practical examples, common mistakes, best practices, and real-world use cases.

What Is the DOM Document

The DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the page as a structured tree of nodes, where each element, attribute, and text is treated as an object.

The document object is the root of this tree. Through it, JavaScript can:

  • Read the content of a web page

  • Change HTML elements and attributes

  • Change CSS styles dynamically

  • Add or remove elements

  • Respond to user actions

Simply put, if JavaScript needs to interact with the web page, it does so through the document.

Why the Document Object Is Important

The document object is important because it allows developers to:

  • Access HTML elements programmatically

  • Build dynamic and interactive user interfaces

  • Update content without reloading the page

  • Validate and process user input

  • Create modern web applications

Without the document object, JavaScript would have no way to understand or control what is displayed on the screen.

Understanding the DOM Tree

Consider this simple HTML:

<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <h1>Hello World</h1>
    <p>Welcome to JavaScript</p>
  </body>
</html>

The DOM represents this as a tree structure:

  • document

    • html

      • head

        • title

      • body

        • h1

        • p

Each part of the HTML becomes a node, and JavaScript can navigate this tree using the document object.

Accessing the Document Object

The document object is automatically available in the browser. You do not need to create it.

console.log(document);

This logs the entire document object, including all elements and methods.

Common Document Properties

document.title

Gets or sets the title of the web page.

console.log(document.title);
document.title = "JavaScript DOM Tutorial";

document.URL

Returns the full URL of the current page.

console.log(document.URL);

document.domain

Returns the domain name of the server.

console.log(document.domain);

document.body

Provides access to the <body> element.

document.body.style.backgroundColor = "lightyellow";

document.head

Provides access to the <head> element.

console.log(document.head);

Selecting Elements Using Document

One of the most common uses of the document object is selecting HTML elements.

getElementById()

Selects an element by its unique ID.

<p id="message">Hello</p>
let msg = document.getElementById("message");
msg.textContent = "Hello Aarushi";

getElementsByClassName()

Selects all elements with a given class name.

<p class="info">One</p>
<p class="info">Two</p>
let items = document.getElementsByClassName("info");
console.log(items.length);

getElementsByTagName()

Selects elements by tag name.

let paragraphs = document.getElementsByTagName("p");
console.log(paragraphs.length);

querySelector()

Selects the first element that matches a CSS selector.

let heading = document.querySelector("h1");
heading.style.color = "blue";

querySelectorAll()

Selects all elements that match a CSS selector.

let listItems = document.querySelectorAll(".info");
listItems.forEach(item => {
    item.style.fontWeight = "bold";
});

Creating and Adding Elements

The document object allows you to create new elements dynamically.

createElement()

let newPara = document.createElement("p");
newPara.textContent = "This is a new paragraph";

appendChild()

document.body.appendChild(newPara);

insertBefore()

let heading = document.querySelector("h1");
document.body.insertBefore(newPara, heading);

Removing Elements

removeChild()

let parent = document.body;
let element = document.getElementById("message");
parent.removeChild(element);

remove()

let para = document.querySelector("p");
para.remove();

Modifying Content Using Document

innerHTML

document.getElementById("content").innerHTML = "<strong>Hello Priya</strong>";

textContent

document.getElementById("content").textContent = "Hello Priya";

textContent is safer because it does not parse HTML.

Handling Events Using Document

The document object can listen to user interactions.

document.addEventListener("click", function() {
    console.log("Document clicked");
});

DOMContentLoaded Event

This ensures the DOM is fully loaded before accessing elements.

document.addEventListener("DOMContentLoaded", function() {
    console.log("DOM is ready");
});

Practical Examples

Example 1: Changing Page Theme

document.getElementById("darkBtn").addEventListener("click", function() {
    document.body.style.backgroundColor = "black";
    document.body.style.color = "white";
});

Example 2: Dynamic List Creation

let ul = document.createElement("ul");

["Aarushi", "Priya", "Saanvi"].forEach(name => {
    let li = document.createElement("li");
    li.textContent = name;
    ul.appendChild(li);
});

document.body.appendChild(ul);

Example 3: Form Validation

document.getElementById("myForm").addEventListener("submit", function(e) {
    let name = document.getElementById("username").value;
    if (name === "") {
        e.preventDefault();
        alert("Name is required");
    }
});

Common Mistakes

  • Accessing elements before the DOM is fully loaded

  • Using innerHTML unnecessarily, leading to security issues

  • Forgetting that getElementsByClassName returns a live collection

  • Not checking if an element exists before using it

  • Mixing up querySelector and querySelectorAll

Best Practices

  • Use DOMContentLoaded or place scripts at the bottom of the page

  • Prefer textContent over innerHTML when possible

  • Cache DOM selections for better performance

  • Keep DOM manipulation minimal inside loops

  • Use clear and meaningful element IDs and classes

Real-World Applications

  • Building interactive dashboards

  • Creating dynamic forms and validations

  • Updating content without page reloads

  • Implementing theme switches and UI effects

  • Developing single-page applications

Summary of JavaScript DOM Document

The JavaScript DOM document object is the foundation of all web page manipulation. It represents the entire HTML document and provides powerful methods and properties to access, modify, create, and remove elements dynamically. By understanding how the document object works, how to select elements, and how to manipulate the DOM efficiently, developers can build responsive, interactive, and user-friendly web applications. Mastering the document object is a crucial step in becoming confident with JavaScript and front-end development.


Practice Questions

  1. Write JavaScript to log the current page title and URL using the Document object.

  2. How would you dynamically change the page title to "My DOM Document Practice"?

  3. Using the Document object, change the background color of the <body> element to light gray.

  4. How can you log the domain of the current webpage using JavaScript?

  5. Using document.head, add a new <meta> element with name="author" and content="Your Name".

  6. Write code to count all <form> elements on the page and display the total number in the console.

  7. Access the first form on the page and set the value of the input field named "username" to "John Doe".

  8. How would you change the target attribute of the first link (<a>) on the page to _blank?

  9. Write JavaScript to update the alt attribute of the first image on the page to "Updated Image".

  10. Using document.createElement and document.createTextNode, create a new paragraph and append it to the <body>.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top