- Home
- /
- JS Document Object
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- JS Document Object
JavaScript Document Object
The document
object is your gateway to controlling the content of a webpage with JavaScript. It represents the DOM (Document Object Model) — the structured layout of HTML elements in a page.
The document
object belongs to the window
, but since it’s globally accessible, you can use it directly.
What Is the Document Object?
The document
object allows you to:
Select and modify HTML elements
Create new elements dynamically
Handle forms, styles, and attributes
Traverse and manipulate the DOM tree
Accessing Elements
1. getElementById()
Fetches a single element by its unique ID:
document.getElementById("greeting").innerHTML = "Hello, Arshyan!";
Best for targeting individual elements like a heading or button.
2. getElementsByClassName()
Returns a live collection of all elements with the given class name:
let items = document.getElementsByClassName("menu-item");
for (let i = 0; i < items.length; i++) {
items[i].style.color = "green";
}
Use when multiple elements share a class (e.g., menu links or cards).
Creating & Adding New Elements
You can build elements from scratch using:
let newPara = document.createElement("p");
let text = document.createTextNode("This paragraph was added using JavaScript!");
newPara.appendChild(text);
document.body.appendChild(newPara);
This dynamically adds new content to your page.
More Useful Document Methods
Method | Description |
---|---|
querySelector() | Returns the first element that matches a CSS selector |
querySelectorAll() | Returns all elements that match a CSS selector |
getElementsByTagName() | Returns elements with a specific tag (e.g., div , li ) |
createElement() | Creates an empty HTML element |
createTextNode() | Creates text to insert inside an element |
appendChild() | Adds a child to an existing element |
removeChild() | Removes a child element |
Example: Adding a Card to the Page
let card = document.createElement("div");
card.className = "card";
card.innerHTML = "JavaScript DOM
This card was created dynamically!
";
document.body.appendChild(card);
This creates a new div
with class card
and inserts it into the page.
Best Practices
Always check if an element exists before modifying it.
Avoid using
innerHTML
when adding user-generated content (for security reasons).Use
querySelector
when you prefer CSS-style selection.
Conclusion
The document
object is the foundation for DOM manipulation in JavaScript. Mastering it unlocks the ability to create interactive, real-time web experiences. Whether you’re updating content, building components, or handling user input — the document
object is your go-to tool.