@@ -25,5 +25,52 @@ For example: document.getElementById("myId") gets a node, and you can change its
25
25
## DOM Tree Example
26
26
![ DOM Tree] ( images/DOMTree.png )
27
27
28
+ ## Accessing and Manipulating the DOM with JavaScript
29
+
30
+ ### 1. Selecting Elements
31
+ ` document.getElementById("myId"); `
32
+ ` document.querySelector(".myClass"); `
33
+ ` document.querySelectorAll("div"); ` <!-- NodeList of all divs -->
34
+
35
+ ### 2. Changing Styles
36
+ ` const title = document.getElementById("title"); `
37
+ ` title.style.backgroundColor = "blue"; `
38
+ ` title.style.color = "white"; `
39
+ ` title.style.padding = "12px"; `
40
+ ` title.style.borderRadius = "15px"; `
41
+
42
+ ### 3. Changing Content
43
+ ` title.textContent = "DOM DOM DOM"; `
44
+ ` title.innerHTML = "<span>DOM</span>"; `
45
+ ` title.innerText = "DOM DOM"; ` <!-- Only shows visibile text -->
46
+
47
+ #### Difference Between textContent, innerHTML, innerText
48
+
49
+ | Property | Description | Includes HTML Tags | Performance | Hidden Elements Affected? |
50
+ | ---------------| -----------------------------------------------------------------------------| ---------------------| --------------| ---------------------------|
51
+ | ` textContent ` | Returns or sets the ** text** content of an element and all its descendants. | ❌ No | ✅ Fast | ❌ No |
52
+ | ` innerHTML ` | Returns or sets the ** HTML markup** inside the element. | ✅ Yes | ⚠️ Slower | ✅ Yes |
53
+ | ` innerText ` | Returns or sets the ** visible text** of the element (CSS-aware). | ❌ No | ⚠️ Slower | ✅ Yes |
54
+
55
+
56
+ - 💡 ** Note:** ` innerText ` is affected by CSS styles (e.g., ` display: none ` ), while ` textContent ` is not.
57
+
58
+ ### 4. Changing Attributes
59
+ ` title.setAttribute("class", "heading common"); `
60
+ ` title.getAttribute("class"); `
61
+ ` title.removeAttribute("class"); `
62
+
63
+ ### 5. Adding/Removing Elements
64
+
65
+
66
+ ### 6. Event Listeners
67
+ ``` javascript
68
+ const btn = document .getElementById (" myBtn" );
69
+ btn .addEventListener (" click" , () => {
70
+ alert (" Button clicked!" );
71
+ });
72
+ ```
73
+
74
+
28
75
### More:
29
76
[ DOM - MDN Web Docs] ( https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction )
0 commit comments