- 1 1. Introduction
- 2 2. What Is the JavaScript document Object?
- 3 3. Key Properties and Methods of the document Object
- 4 4. Selecting and Manipulating HTML Elements (With Code Examples)
- 5 5. Steps to Create and Append New Elements (With Diagrams)
- 6 6. How to Set Up Event Listeners (Practical Examples)
- 7 7. Common Practical Use Cases and Applied Scenarios
- 8 8. Cautions and Best Practices
- 9 9. FAQ: Common Questions for Beginners
- 10 10. Conclusion and Next Steps
1. Introduction
JavaScript is an essential programming language for web development. Among its core features, the document object plays a central role in controlling and manipulating a web page’s structure and content. In this article, you will learn the JavaScript document object in a way that beginners to intermediate users can understand.
What is JavaScript used for?
JavaScript is a programming language used together with HTML and CSS, mainly to create dynamic behaviors and user interactions on web pages. Examples include form input validation, displaying popup menus, and adding animation effects.
In particular, the document object provides functionality for accessing and editing elements on a web page using JavaScript. With this object, you can select HTML elements, add new elements, set events, and perform many other operations.
Why do you need to learn the document object?
The document object functions as part of the DOM (Document Object Model). The DOM is a model that represents the structure of an HTML or XML document in a way that can be manipulated programmatically, and it is essentially required knowledge for web development.
By understanding this model and learning how to use the document object effectively, you can handle situations such as the following:
- Dynamic updates to the user interface
- Real-time form validation
- Asynchronous data loading and rendering (AJAX or Fetch API)
- Implementing modal windows and popup menus
What you will learn in this article
This article explains everything from the basics to more advanced usage of the document object in an organized way, using practical code examples to show how it works. After reading, you will be able to understand the following:
- The basic structure and functionality of the document object
- How to select and manipulate HTML elements
- How to set up event listeners and practical usage examples
- Important cautions and best practices
Beginners can firmly grasp the fundamentals, while intermediate users can gain hints for writing more efficient code.
2. What Is the JavaScript document Object?
In JavaScript, the document object is one of the most important interfaces for working with web pages. Provided as part of the DOM (Document Object Model), it allows you to easily manipulate and modify elements inside a web page.
The role of the document object
The document object represents the entire HTML document loaded by the browser. This enables you to control the HTML structure, styles, and content programmatically using JavaScript.
For example, you can do the following:
- Select and edit HTML elements
- Create and append new elements
- Change the page background color or text content
- Detect user actions by setting event listeners
Relationship between the DOM and the document object
The DOM (Document Object Model) represents an HTML or XML document as a tree structure. At the top of that tree is the document object.
The diagram below shows a simple view of the relationship between the DOM and the document object.
document
├── html
│ ├── head
│ │ └── title
│ └── body
│ ├── div
│ ├── p
│ └── buttonIn this way, the document object represents the entire page as a tree and serves as the starting point for accessing each element.
Basic usage of the document object
Let’s look at a few simple examples of using the document object.
Example 1: Get the page title
console.log(document.title); // Get the page titleExample 2: Change the background color
document.body.style.backgroundColor = "lightblue";Example 3: Select and edit an element
let heading = document.getElementById("main-title");
heading.textContent = "New Title";By combining these operations, you can build interactive and dynamic web pages.
Key features of the document object
- Real-time updates
– Changes to the document are reflected immediately. - Access to a hierarchical structure
– You can flexibly select and modify elements by traversing the DOM tree. - Event management
– You can add event listeners based on user actions.

3. Key Properties and Methods of the document Object
The JavaScript document object provides many properties and methods that support a wide range of web page operations. In this section, we will introduce commonly used properties and methods.
1. Commonly used properties
Below are commonly used properties of the document object and what they are used for.
| Property | Description | Example |
|---|---|---|
document.title | Gets or sets the current page title. | console.log(document.title); |
document.URL | Gets the URL of the current page. | console.log(document.URL); |
document.body | Gets the page’s <body> element. | document.body.style.backgroundColor = "yellow"; |
document.head | Gets the page’s <head> element. | console.log(document.head.innerHTML); |
document.forms | Gets all form elements on the page. | console.log(document.forms[0]); |
document.images | Gets all image elements on the page. | console.log(document.images); |
document.links | Gets all link elements on the page. | console.log(document.links); |
document.cookie | Gets or sets cookie information for the page. | console.log(document.cookie); |
document.documentElement | Gets the <html> element representing the entire page. | console.log(document.documentElement); |
These properties help you easily retrieve and update information about a web page.
2. Commonly used methods
Next, here are methods used to manipulate elements and add new elements.
| Method | Description | Example |
|---|---|---|
getElementById(id) | Selects an element with the specified ID attribute. | let element = document.getElementById("header"); |
getElementsByClassName(class) | Selects all elements with the specified class name (returned as an HTMLCollection). | let items = document.getElementsByClassName("item"); |
getElementsByTagName(tag) | Selects all elements with the specified tag name. | let paragraphs = document.getElementsByTagName("p"); |
querySelector(selector) | Selects the first element that matches the CSS selector. | let firstDiv = document.querySelector("div.container"); |
querySelectorAll(selector) | Selects all elements that match the CSS selector (returned as a NodeList). | let allDivs = document.querySelectorAll("div.container"); |
createElement(tag) | Creates a new HTML element. | let newDiv = document.createElement("div"); |
appendChild(node) | Adds a new child node to the specified element. | document.body.appendChild(newDiv); |
removeChild(node) | Removes the specified child node. | document.body.removeChild(newDiv); |
write(content) | Writes HTML or text directly into the document (deprecated). | document.write("<h1>Hello World!</h1>"); |
addEventListener(event, func) | Adds an event listener to an element for a specified event. | document.addEventListener("click", () => { alert("Clicked!"); }); |
3. Examples combining properties and methods
Let’s look at real usage examples.
Example 1: Get a form value
let form = document.forms[0];
let input = form.elements["username"];
console.log(input.value);Example 2: Create and append a new element
let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
document.body.appendChild(newParagraph);Example 3: Add a click event
document.getElementById("myButton").addEventListener("click", () => {
alert("The button was clicked!");
});4. Summary
The document object provides a rich set of properties and methods that are useful for manipulating web pages. By mastering them, you can create more interactive and functional web pages.
4. Selecting and Manipulating HTML Elements (With Code Examples)
By using JavaScript’s document object, you can easily select HTML elements, edit their content, and change their attributes. In this section, we will explain common selection and manipulation techniques in detail with code examples.
1. How to Select HTML Elements
1-1. Select by ID – getElementById()
Select elements using the ID attribute set on an HTML element.
Example: Change an element’s text
HTML:
<h1 id="title">Original Title</h1>JavaScript:
let title = document.getElementById("title");
title.textContent = "New Title"; // Change the textKey point
- An ID must be unique. You cannot assign the same ID to multiple elements.
1-2. Select by class name – getElementsByClassName()
Select multiple elements that share the same class name.
Example: Change the background color
HTML:
<div class="box">Box 1</div>
<div class="box">Box 2</div>JavaScript:
let boxes = document.getElementsByClassName("box");
for (let i = 0; i < boxes.length; i++) {
boxes[i].style.backgroundColor = "lightblue";
}Key point
- You iterate over the elements like an array and manipulate them one by one.
1-3. Select by tag name – getElementsByTagName()
Select all elements with the specified tag name.
Example: Change the color of all paragraphs
HTML:
<p>Paragraph 1</p>
<p>Paragraph 2</p>JavaScript:
let paragraphs = document.getElementsByTagName("p");
for (let p of paragraphs) {
p.style.color = "green";
}1-4. Select with CSS selectors – querySelector() and querySelectorAll()
Using CSS selectors lets you select elements more flexibly.
Select a single element – querySelector()
let firstDiv = document.querySelector("div.box");
firstDiv.textContent = "Selected box";Select multiple elements – querySelectorAll()
let allDivs = document.querySelectorAll("div.box");
allDivs.forEach(div => div.style.border = "1px solid red");2. How to Manipulate HTML Elements
2-1. Editing text or HTML
Example: Difference between innerHTML and textContent
HTML:
<div id="content">Original text</div>JavaScript:
let content = document.getElementById("content");
// Change text only
content.textContent = "<b>New text</b>"; // Displayed as plain text
// Change including HTML
content.innerHTML = "<b>New text</b>"; // Displayed in boldKey points
textContenttreats tags as a plain string and does not interpret them as HTML.innerHTMLapplies HTML directly, but you must be careful about security (XSS prevention).
2-2. Editing attributes
Example: Change a link
HTML:
<a id="link" href="https://example.com">Original link</a>JavaScript:
let link = document.getElementById("link");
link.setAttribute("href", "https://google.com"); // Change the URL
link.textContent = "Link to Google"; // Change the label2-3. Creating and appending new elements
Example: Add a new list item
HTML:
<ul id="list">
<li>Item 1</li>
</ul>JavaScript:
let list = document.getElementById("list");
let newItem = document.createElement("li");
newItem.textContent = "Item 2"; // Create a new item
list.appendChild(newItem); // Append to the end of the list2-4. Removing elements
Example: Remove an element when clicking a button
HTML:
<div id="box">Element to be removed</div>
<button id="deleteBtn">Remove</button>JavaScript:
let box = document.getElementById("box");
let deleteBtn = document.getElementById("deleteBtn");
deleteBtn.addEventListener("click", () => {
box.remove(); // Remove the element
});3. Summary
In this section, you learned how to select and manipulate HTML elements using the document object through practical examples. Mastering these techniques makes dynamic control of web pages much easier.

5. Steps to Create and Append New Elements (With Diagrams)
Using JavaScript’s document object, you can dynamically create new HTML elements and append them to an existing page. In this section, we explain the specific steps for creating and appending elements with code examples and diagrams.
1. How to create new elements
1-1. Create an element – createElement()
Create a new HTML element using the document.createElement() method.
Example: Create a new paragraph element
let newParagraph = document.createElement("p"); // Create a new <p> element
newParagraph.textContent = "This paragraph was added dynamically."; // Set the textKey points
- The created element has not been added to the DOM yet.
- You can freely set text and attributes.
2. Set attributes and styles on an element
2-1. Set attributes – setAttribute()
To set attributes on a created element, use the setAttribute() method.
Example: Add attributes to a link element
let link = document.createElement("a");
link.textContent = "Google";
link.setAttribute("href", "https://google.com"); // Set the URL
link.setAttribute("target", "_blank"); // Open in a new tab2-2. Set styles – the style property
If you want to set the design directly, use the style property.
Example: Style a button
let button = document.createElement("button");
button.textContent = "Click";
button.style.backgroundColor = "blue"; // Background color
button.style.color = "white"; // Text color
button.style.padding = "10px 20px"; // Padding3. Append the element to the page
You can append created elements to the DOM using appendChild() or insertBefore().
3-1. Append to the end – appendChild()
Example: Append a list item
HTML:
<ul id="list">
<li>Item 1</li>
</ul>JavaScript:
let list = document.getElementById("list");
let newItem = document.createElement("li");
newItem.textContent = "Item 2"; // Create a new item
list.appendChild(newItem); // Append to the end of the list3-2. Append at a specific position – insertBefore()
Example: Insert an item at a specified position
let referenceItem = list.firstElementChild; // Use the first item as a reference
list.insertBefore(newItem, referenceItem); // Insert before the first item4. Remove elements
You can remove created elements using removeChild() or remove().
4-1. Remove a child element – removeChild()
let itemToRemove = list.lastElementChild; // Get the last item
list.removeChild(itemToRemove); // Remove it4-2. Remove the element itself – remove()
newItem.remove(); // Remove itself5. Practical example: Dynamically creating a card element
Below is an example that dynamically creates a new “card” element, sets styles, and appends it to the page.
HTML:
<div id="container"></div>JavaScript:
let container = document.getElementById("container");
// Create the card element
let card = document.createElement("div");
card.classList.add("card"); // Add a class
// Create the card title
let title = document.createElement("h2");
title.textContent = "Card Title";
// Create the card body text
let description = document.createElement("p");
description.textContent = "This is the description text for the card.";
// Assemble and append
card.appendChild(title);
card.appendChild(description);
container.appendChild(card); // Append to the page
// Styling
card.style.border = "1px solid #ccc";
card.style.padding = "10px";
card.style.margin = "10px";
card.style.width = "200px";
card.style.boxShadow = "0 4px 6px rgba(0, 0, 0, 0.1)";Result:
Card Title
This is the description text for the card.6. Summary
In this section, you learned the full workflow from creating new elements to setting attributes and styles, and appending them to the page. By applying these techniques, generating dynamic web content becomes much easier.
6. How to Set Up Event Listeners (Practical Examples)
In JavaScript, you can use the document object to set up event listeners and execute dynamic processing in response to user actions. In this section, we explain everything from the basics of event listeners to practical usage examples.
1. What is an event listener?
An event listener is a mechanism that detects user actions (such as clicks, input, or mouse movement) and executes a corresponding operation.
Example: Basic click event
document.getElementById("myButton").addEventListener("click", () => {
alert("The button was clicked!");
});2. How to add event listeners
2-1. Basic usage of addEventListener()
The addEventListener() method uses the following syntax:
element.addEventListener(event, function, useCapture);Parameter description
event– The event type (for example:click,mouseover,keydown).function– The function to execute (anonymous or named).useCapture– Event propagation method (truefor capture,falsefor bubbling).
Example: Add a mouseover event
let box = document.getElementById("box");
box.addEventListener("mouseover", () => {
box.style.backgroundColor = "lightblue";
});3. Commonly used event types
Below are commonly used event types and examples.
| Event | Description | Example |
|---|---|---|
click | When an element is clicked | Button click handling |
dblclick | When an element is double-clicked | Selecting text |
mouseover | When the mouse pointer enters an element | Start hover animation |
mouseout | When the mouse pointer leaves an element | End hover animation |
keydown | When a key is pressed | Detect keyboard input |
keyup | When a key is released | Validate input after typing |
submit | When a form is submitted | Validate form data |
focus | When an element receives focus | Auto-assist input fields |
blur | When an element loses focus | Input error checking |
4. Practical event listener examples
4-1. Change text by clicking a button
HTML:
<button id="changeText">Change</button>
<p id="text">Original text</p>JavaScript:
let button = document.getElementById("changeText");
let text = document.getElementById("text");
button.addEventListener("click", () => {
text.textContent = "New text";
});4-2. Real-time input detection
HTML:
<input type="text" id="nameInput" placeholder="Enter your name">
<p id="output"></p>JavaScript:
let input = document.getElementById("nameInput");
let output = document.getElementById("output");
input.addEventListener("input", () => {
output.textContent = "Input: " + input.value;
});4-3. Change background color on hover
HTML:
<div id="hoverBox" style="width: 100px; height: 100px; background-color: lightgray;"></div>JavaScript:
let hoverBox = document.getElementById("hoverBox");
hoverBox.addEventListener("mouseover", () => {
hoverBox.style.backgroundColor = "yellow";
});
hoverBox.addEventListener("mouseout", () => {
hoverBox.style.backgroundColor = "lightgray";
});5. How to remove event listeners
You can remove an event listener using the removeEventListener() method.
Example: Remove a click event
function handleClick() {
alert("Clicked!");
}
let button = document.getElementById("myButton");
button.addEventListener("click", handleClick);
// Remove the event listener
button.removeEventListener("click", handleClick);Important note
- To remove an event listener, you must reference the same function. Anonymous functions cannot be removed.
6. Summary
In this section, you learned how to set up event listeners, common event types, and practical usage examples. Mastering event handling is essential for creating interactive web applications.

7. Common Practical Use Cases and Applied Scenarios
The JavaScript document object can be applied in many real-world scenarios. In this section, we introduce common use cases and applied scenarios frequently seen in actual development.
1. Dynamic form validation
Form input validation is important for improving user experience. Below is an example that checks input in real time.
HTML
<form id="signupForm">
<label for="email">Email:</label>
<input type="email" id="email" required>
<span id="emailError" style="color: red;"></span>
<br>
<button type="submit">Submit</button>
</form>JavaScript
let emailInput = document.getElementById("email");
let emailError = document.getElementById("emailError");
let form = document.getElementById("signupForm");
// Input validation
emailInput.addEventListener("input", () => {
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(emailInput.value)) {
emailError.textContent = "Please enter a valid email address.";
} else {
emailError.textContent = "";
}
});
// Check on form submission
form.addEventListener("submit", (event) => {
if (emailError.textContent !== "") {
event.preventDefault();
alert("There is an error in your input.");
}
});2. Dynamic content generation
This example dynamically generates new elements based on user actions.
HTML
<div id="container"></div>
<button id="addItem">Add item</button>JavaScript
let container = document.getElementById("container");
let addButton = document.getElementById("addItem");
addButton.addEventListener("click", () => {
let newItem = document.createElement("div");
newItem.textContent = "New item";
newItem.style.border = "1px solid #ccc";
newItem.style.padding = "10px";
newItem.style.margin = "5px 0";
container.appendChild(newItem);
});Result: A new item is added each time the button is clicked.
8. Cautions and Best Practices
The JavaScript document object is very powerful, but improper usage can negatively impact performance and security. In this section, we introduce important cautions and best practices to keep your code safe and efficient.
1. Performance optimization
1-1. Minimize DOM operations
DOM operations are costly, so you should reduce the number of times they are performed.
Bad example (repeated DOM operations inside a loop)
for (let i = 0; i < 100; i++) {
let div = document.createElement("div");
div.textContent = "Item " + i;
document.body.appendChild(div);
}Improved example (using a Document Fragment)
let fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
let div = document.createElement("div");
div.textContent = "Item " + i;
fragment.appendChild(div);
}
document.body.appendChild(fragment);Key point
- Fragments can be appended to the DOM in a single operation, improving performance.
1-2. Reduce reflow and repaint
Frequently changing styles causes reflow and repaint, which can slow down rendering.
Bad example
let box = document.getElementById("box");
box.style.width = "100px";
box.style.height = "100px";
box.style.backgroundColor = "red";Improved example (batch updates)
let box = document.getElementById("box");
Object.assign(box.style, {
width: "100px",
height: "100px",
backgroundColor: "red"
});2. Security considerations
2-1. Preventing XSS attacks
Using innerHTML can allow malicious scripts to be injected.
Dangerous example
let userInput = "<script>alert('Attack!')</script>";
document.getElementById("output").innerHTML = userInput;Safe example
let userInput = "<script>alert('Attack!')</script>";
document.getElementById("output").textContent = userInput;Key point
- Always sanitize user input before displaying it.
2-2. Proper management of event listeners
If unused event listeners are not removed, they may cause memory leaks.
Bad example
document.getElementById("button").addEventListener("click", () => {
alert("Clicked!");
});Improved example (remove the listener when no longer needed)
function handleClick() {
alert("Clicked!");
}
let button = document.getElementById("button");
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);3. Readability and maintainability
3-1. Consistent naming conventions
Use descriptive variable and function names that clearly indicate their roles.
Bad example
let a = document.getElementById("username");
let b = document.getElementById("password");Improved example
let usernameInput = document.getElementById("username");
let passwordInput = document.getElementById("password");3-2. Creating reusable functions
By refactoring code into functions, you reduce duplication and improve maintainability.
Bad example
document.getElementById("btn1").addEventListener("click", () => alert("Button 1"));
document.getElementById("btn2").addEventListener("click", () => alert("Button 2"));Improved example
function handleClick(message) {
alert(message);
}
document.getElementById("btn1").addEventListener("click", () => handleClick("Button 1"));
document.getElementById("btn2").addEventListener("click", () => handleClick("Button 2"));4. Mobile and responsive considerations
When using JavaScript, ensure smooth behavior on mobile devices as well.
Tips and countermeasures
- Alternative to click events – On mobile, consider
touchstartortouchend. - Viewport settings – Properly configure the viewport to prevent unwanted zooming.
<meta name="viewport" content="width=device-width, initial-scale=1.0">- Combine with media queries – Use CSS media queries for responsive layouts.
5. Summary
This section covered important cautions and best practices for using the document object safely and efficiently.
- Performance optimization: Minimize DOM operations.
- Security: Prevent XSS and handle user input safely.
- Maintainability: Write readable and reusable code.
- Mobile support: Consider responsive design and touch events.

9. FAQ: Common Questions for Beginners
Beginners who start using the JavaScript document object often encounter various questions and issues. This section answers common questions in a Q&A format.
Q1. Why can’t I select an element using getElementById()?
A:
Common reasons include the following:
- Incorrect ID
- The specified ID does not exist or is misspelled.
- Solution: Check that the ID in your HTML matches the one in your JavaScript.
- Script execution timing
- If JavaScript runs before the HTML is loaded, the element does not exist yet.
- Solution: Use the
DOMContentLoadedevent.
document.addEventListener("DOMContentLoaded", () => {
let element = document.getElementById("myDiv");
console.log(element.textContent);
});Q2. What is the difference between innerHTML and textContent?
A:
innerHTML: Gets or sets all content including HTML tags.textContent: Gets or sets only text content (HTML tags are ignored).
Q3. Why can’t I modify elements returned by querySelectorAll()?
A:querySelectorAll() returns a static NodeList, which is not an array. You must loop over it to apply changes.
let items = document.querySelectorAll(".item");
items.forEach(item => {
item.style.color = "blue";
});Q4. Why doesn’t addEventListener() work?
A:
Possible reasons include:
- Element not found
- The target element was not selected correctly.
- Solution: Check in the console whether the element exists.
Q5. Why does removeChild() throw an error?
A:
The element to be removed must be a child of the parent element.
let list = document.getElementById("list");
let item = document.getElementById("item1");
list.removeChild(item);6. Summary
This FAQ section addressed common beginner issues. Paying attention to element selection, timing, and proper method usage will help you avoid many problems.
10. Conclusion and Next Steps
Throughout this article, you have learned the JavaScript document object from basic concepts to practical applications. Let’s review the key points and look at the next steps for further learning.
By mastering the document object, you gain the foundation needed to build dynamic, interactive, and efficient web applications. As your next step, explore advanced DOM manipulation, API integration, and modern frameworks to further enhance your skills.



