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() |
