|
1 | 1 | /* |
2 | | -# DOM (Document Object Model) in JavaScript - Full In-Depth Explanation |
3 | | -
|
4 | | ---- |
5 | | -
|
6 | | -## What is the DOM? |
7 | | -
|
8 | | -The Document Object Model (DOM) is a **programming interface** provided by the browser that represents the structure of a webpage. It converts the HTML document into a **tree of JavaScript objects** so you can manipulate content, structure, and style dynamically. |
9 | | -
|
10 | | -The DOM represents: |
11 | | -
|
12 | | -* Each **HTML element** as a **node object**. |
13 | | -* The whole document as a `document` object. |
14 | | -
|
15 | | ---- |
16 | | -
|
17 | | -## DOM Tree Structure |
18 | | -
|
19 | | -* **Document**: The root node of the document. |
20 | | -* **Element**: Each tag becomes an element node. |
21 | | -* **Text**: Inside each tag, text is also a node. |
22 | | -* **Attributes**: HTML attributes (e.g., class, id) are part of element nodes. |
23 | | -
|
24 | | -It creates a **tree-like structure** of nested elements. |
25 | | -
|
26 | | ---- |
27 | | -
|
28 | | -## Element Selection Methods |
29 | | -
|
30 | | -### 1. `getElementById()` - Selects by unique ID. |
31 | | -
|
32 | | -### 2. `getElementsByClassName()` - Selects by class name (returns a live HTMLCollection). |
33 | | -
|
34 | | -### 3. `getElementsByTagName()` - Selects by tag name (live HTMLCollection). |
35 | | -
|
36 | | -### 4. `querySelector()` - Selects the first matching CSS selector. |
37 | | -
|
38 | | -### 5. `querySelectorAll()` - Selects all matching CSS selectors (NodeList). |
39 | | -
|
40 | | ---- |
41 | | -
|
42 | | -## Reading and Changing Content |
43 | | -
|
44 | | -### `textContent` |
45 | | -
|
46 | | -* Returns the text content of an element and all its children. |
47 | | -* Ignores CSS styles (hidden or shown). |
48 | | -* Best for reading/writing raw text. |
49 | | -
|
50 | | -### `innerText` |
51 | | -
|
52 | | -* Similar to `textContent` but respects CSS styling. |
53 | | -* Only shows visible text. |
54 | | -* Can trigger reflow and repaint (performance impact). |
55 | | -
|
56 | | -### `innerHTML` |
57 | | -
|
58 | | -* Returns the HTML content as a string. |
59 | | -* Can be used to insert HTML markup (risky for XSS). |
60 | | -
|
61 | | -### `outerHTML` |
62 | | -
|
63 | | -* Returns the HTML of the element **including the element itself**. |
64 | | -* Can replace the entire element. |
65 | | -
|
66 | | -### `nodeValue` |
67 | | -
|
68 | | -* Works on text nodes, not commonly used directly on elements. |
69 | | -
|
70 | | ---- |
71 | | -
|
72 | | -## Attributes in DOM |
73 | | -
|
74 | | -### Accessing Attributes |
75 | | -
|
76 | | -* `getAttribute('attributeName')` – Reads attribute value. |
77 | | -* `setAttribute('attributeName', value)` – Sets attribute. |
78 | | -* `removeAttribute('attributeName')` – Removes attribute. |
79 | | -* `hasAttribute('attributeName')` – Checks if attribute exists. |
80 | | -
|
81 | | -### Standard Attributes |
82 | | -
|
83 | | -* `id`, `class`, `href`, `src`, `alt`, `type`, `value`, etc. |
84 | | -
|
85 | | -### Custom Data Attributes (data-\*) |
86 | | -
|
87 | | -* Accessible using the `dataset` property. |
88 | | -* `element.dataset.key` |
89 | | -
|
90 | | ---- |
91 | | -
|
92 | | -## Working with Classes |
93 | | -
|
94 | | -### `className` |
95 | | -
|
96 | | -* Directly gets/sets the `class` attribute as a string. |
97 | | -
|
98 | | -### `classList` |
99 | | -
|
100 | | -* Provides methods to work with classes: |
101 | | -
|
102 | | - * `add()` |
103 | | - * `remove()` |
104 | | - * `toggle()` |
105 | | - * `contains()` |
106 | | - * `replace()` |
107 | | -
|
108 | | ---- |
109 | | -
|
110 | | -## Styling Elements |
111 | | -
|
112 | | -### `element.style` |
113 | | -
|
114 | | -* Inline styles only. |
115 | | -* Access and change individual CSS properties. |
116 | | -
|
117 | | -### Best Practice |
118 | | -
|
119 | | -* Prefer `classList` manipulation to apply CSS classes for multiple style changes. |
120 | | -
|
121 | | ---- |
122 | | -
|
123 | | -## DOM Traversal (Navigating the DOM) |
124 | | -
|
125 | | -### Parent/Child |
126 | | -
|
127 | | -* `parentNode` |
128 | | -* `childNodes` (includes text nodes) |
129 | | -* `children` (only elements) |
130 | | -* `firstChild`, `lastChild` |
131 | | -* `firstElementChild`, `lastElementChild` |
132 | | -
|
133 | | -### Siblings |
134 | | -
|
135 | | -* `nextSibling`, `previousSibling` (includes text nodes) |
136 | | -* `nextElementSibling`, `previousElementSibling` |
137 | | -
|
138 | | ---- |
139 | | -
|
140 | | -## Creating and Modifying Elements |
141 | | -
|
142 | | -### Creating Elements |
143 | | -
|
144 | | -* `document.createElement('tagName')` |
145 | | -* `document.createTextNode('text')` |
146 | | -
|
147 | | -### Appending Elements |
148 | | -
|
149 | | -* `parent.appendChild(child)` |
150 | | -* `parent.insertBefore(newEl, referenceEl)` |
151 | | -* `parent.append()` / `prepend()` |
152 | | -
|
153 | | -### Removing/Replacing Elements |
154 | | -
|
155 | | -* `element.remove()` |
156 | | -* `parent.removeChild(child)` |
157 | | -* `parent.replaceChild(newChild, oldChild)` |
158 | | -
|
159 | | ---- |
160 | | -
|
161 | | -## DOM Events (Brief Overview) |
162 | | -
|
163 | | -* `addEventListener('eventType', callback)` |
164 | | -* Mouse Events: `click`, `dblclick`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave` |
165 | | -* Keyboard Events: `keydown`, `keyup`, `keypress` |
166 | | -* Form Events: `submit`, `change`, `input`, `focus`, `blur` |
167 | | -
|
168 | | ---- |
169 | | -
|
170 | | -## DOMContentLoaded vs window\.onload |
171 | | -
|
172 | | -* `DOMContentLoaded`: Triggers when the DOM is fully parsed (recommended). |
173 | | -* `window.onload`: Triggers after all content, including images, is fully loaded. |
174 | | -
|
175 | | ---- |
176 | | -
|
177 | | -## Additional Advanced Concepts |
178 | | -
|
179 | | -### `documentFragment` |
180 | | -
|
181 | | -* A lightweight container to batch DOM changes for performance. |
182 | | -
|
183 | | -### `cloneNode()` |
184 | | -
|
185 | | -* Clones a DOM node. Use `cloneNode(true)` for deep clone. |
186 | | -
|
187 | | -### `isEqualNode()` / `isSameNode()` |
188 | | -
|
189 | | -* Compare two nodes for structural and value equality. |
190 | | -
|
191 | | -### Shadow DOM |
192 | | -
|
193 | | -* Encapsulation method for components (used in Web Components). |
194 | | -
|
195 | | ---- |
| 2 | +1. What is DOM? |
| 3 | +Tree structure of the HTML page |
| 4 | +JavaScript can read/manipulate it |
| 5 | +Starts with window -> document -> html -> head/body -> elements |
| 6 | +*/ |
196 | 7 |
|
197 | | -Let me know if you'd like detailed examples of any of these or want to dive into event delegation, mutation observers, or Shadow DOM next. |
| 8 | +// 2. Window Object (Global Scope) |
| 9 | +window.alert("Hi!"); |
| 10 | +window.location.href; // Current URL |
| 11 | +window.innerWidth; // Width of viewport |
| 12 | +window.setTimeout(fn, 1000); // Call function later |
| 13 | +console.log(window.document); // Whole DOM |
| 14 | + |
| 15 | +// 3. Document Object |
| 16 | +document.title = "New Page"; |
| 17 | +console.log(document.body); |
| 18 | +document.body.style.background = "lightblue"; |
| 19 | +document.URL; |
| 20 | +document.querySelector("h1").innerText; |
| 21 | + |
| 22 | +// 4. Selecting Elements (5 Key Methods) |
| 23 | +document.getElementById("myId"); |
| 24 | +document.getElementsByClassName("card"); |
| 25 | +document.getElementsByTagName("section"); |
| 26 | +document.querySelector(".hero"); |
| 27 | +document.querySelectorAll("ul li"); |
| 28 | + |
| 29 | +// 5. Styling Elements |
| 30 | +el.style.backgroundColor = "black"; |
| 31 | +el.style.color = "white"; |
| 32 | +el.style.fontSize = "24px"; |
| 33 | +el.style.padding = "10px"; |
| 34 | +el.style.border = "1px solid #ccc"; |
| 35 | + |
| 36 | +// 6. Content Change (Text, HTML) |
| 37 | +el.innerText = "New text"; |
| 38 | +el.textContent = "Hello World"; |
| 39 | +el.innerHTML = "<strong>Bold</strong>"; |
| 40 | + |
| 41 | +// 7. Attributes (Set/Get/Remove/Has) |
| 42 | +el.setAttribute("href", "https://google.com"); |
| 43 | +let val = el.getAttribute("class"); |
| 44 | +el.removeAttribute("disabled"); |
| 45 | +let has = el.hasAttribute("title"); |
| 46 | +el.setAttribute("data-user", "john123"); |
| 47 | + |
| 48 | +// 8. ClassList (CSS Classes) |
| 49 | +el.classList.add("active"); |
| 50 | +el.classList.remove("hidden"); |
| 51 | +el.classList.toggle("open"); |
| 52 | +el.classList.contains("selected"); // true/false |
| 53 | +el.classList.replace("old", "new"); |
| 54 | + |
| 55 | +// 9. Events (Click, Hover, Input, Submit, etc.) |
| 56 | +el.addEventListener("click", () => alert("Clicked!")); |
| 57 | +el.addEventListener("mouseover", () => console.log("Hovered!")); |
| 58 | +input.addEventListener("input", (e) => console.log(e.target.value)); |
| 59 | +form.addEventListener("submit", (e) => e.preventDefault()); |
| 60 | +window.addEventListener("scroll", () => console.log("scrolling")); |
| 61 | + |
| 62 | +// 10. Creating & Appending Elements |
| 63 | +let p = document.createElement("p"); |
| 64 | +p.innerText = "New paragraph"; |
| 65 | +document.body.appendChild(p); |
| 66 | +let btn = document.createElement("button"); |
| 67 | +btn.setAttribute("class", "btn"); |
| 68 | +btn.textContent = "Click Me"; |
| 69 | +document.querySelector("#container").appendChild(btn); |
| 70 | + |
| 71 | +// 11. Removing Elements |
| 72 | +el.remove(); |
| 73 | +parent.removeChild(child); |
| 74 | +container.innerHTML = ""; // clear all |
| 75 | + |
| 76 | +// 12. NodeList vs HTMLCollection |
| 77 | +let nodeList = document.querySelectorAll("li"); |
| 78 | +nodeList.forEach((el) => console.log(el)); |
| 79 | +let htmlCollection = document.getElementsByClassName("box"); |
| 80 | +Array.from(htmlCollection).forEach((el) => console.log(el)); |
| 81 | + |
| 82 | +// 13. Forms & Input Fields |
| 83 | +let input = document.querySelector("#name"); |
| 84 | +input.value = "John"; // Set value |
| 85 | +input.getAttribute("placeholder"); |
| 86 | +input.setAttribute("placeholder", "Enter name"); |
| 87 | +form.addEventListener("submit", (e) => { |
| 88 | + e.preventDefault(); |
| 89 | + console.log(input.value); |
| 90 | +}); |
| 91 | + |
| 92 | +// 14. Traversing DOM (Parent, Children, Siblings) |
| 93 | +el.parentElement; |
| 94 | +el.children; // HTMLCollection |
| 95 | +el.firstElementChild; |
| 96 | +el.lastElementChild; |
| 97 | +el.nextElementSibling; |
| 98 | +el.previousElementSibling; |
| 99 | + |
| 100 | +// 15. Cloning Elements |
| 101 | +let copy = el.cloneNode(true); // true = deep clone |
| 102 | +document.body.appendChild(copy); |
| 103 | + |
| 104 | +// 16. Modifying Classes Based on Condition |
| 105 | +if (!el.classList.contains("active")) { |
| 106 | + el.classList.add("active"); |
| 107 | +} else { |
| 108 | + el.classList.remove("active"); |
| 109 | +} |
| 110 | +// 17. Setting Styles Dynamically |
| 111 | +function toggleTheme() { |
| 112 | + let body = document.body; |
| 113 | + body.classList.toggle("dark-mode"); |
| 114 | +} |
| 115 | +/* |
| 116 | +18. Useful Real-world Examples |
| 117 | +Toggle mobile menu |
| 118 | +Validate form input |
| 119 | +Show/hide password |
| 120 | +Change theme (dark/light) |
| 121 | +Load content dynamically with .innerHTML |
198 | 122 | */ |
0 commit comments