JavaScript DOM

JavaScript DOM (Document Object Model)
The DOM is a programming interface that allows JavaScript to interact with and manipulate web pages.
When a web page loads, the browser converts the HTML into a tree structure called the DOM Tree.
Example HTML:
Browser Converts It to a DOM Structure:
Why Do We Use DOM?
With the DOM, JavaScript can:
- Change HTML content
- Modify styles
- Add or remove elements
- Handle events (click, hover, keypress, etc.)
Selecting Elements
| Method | Example | Purpose |
|---|---|---|
getElementById() | document.getElementById("title") | Select by ID |
getElementsByClassName() | document.getElementsByClassName("text") | Select by class |
querySelector() | document.querySelector("p") | Select single element |
querySelectorAll() | document.querySelectorAll("p") | Select multiple |
Example: Change Text
Example: Change CSS Style
Working with Attributes
Creating and Adding Elements
Removing Elements
Handling Events
DOM Levels
| Level | Description |
|---|---|
| DOM Level 0 | Basic event model |
| DOM Level 1 | Node and document structure |
| DOM Level 2 | Style and advanced events |
| DOM Level 3 | Validation and XPath support |
Summary
| DOM Feature | Purpose |
|---|---|
| Read content | innerHTML, textContent |
| Modify content | innerHTML = ... |
| Style elements | .style.property = value |
| Create/remove elements | createElement(), remove() |
| Add events | addEventListener() |
