|
| 1 | +--- |
| 2 | +title: 'DOM manipulation in JavaScript' |
| 3 | +sidebar_label: DOM-manipulation-in-JavaScript |
| 4 | +authors: [dharshibalasubramaniyam] |
| 5 | +tags: [dom, javascript] |
| 6 | +date: 2024-06-25 |
| 7 | +hide_table_of_contents: true |
| 8 | +--- |
| 9 | + |
| 10 | +## 1. Understanding DOM |
| 11 | + |
| 12 | +- The Document Object Model (DOM) is a programming interface for web documents. |
| 13 | + |
| 14 | +- This model allows developers to interact with the document programmatically via scripting languages like JavaScript. |
| 15 | + |
| 16 | +- When a web page is loaded, the browser parses the HTML and creates the DOM. |
| 17 | + |
| 18 | +- The DOM represents the document as a tree of nodes, where each node is an object representing a part of the document: |
| 19 | + |
| 20 | +*Document Node*: Represents the entire document. |
| 21 | + |
| 22 | +*Element Nodes*: Represent HTML elements like `<div>`, `<p>`, `<a>`, etc. |
| 23 | + |
| 24 | +*Text Nodes*: Contain the text content within elements. |
| 25 | + |
| 26 | +*Attribute Nodes*: Represent the attributes of HTML elements (`class`, `id`, `src` etc.). |
| 27 | + |
| 28 | +For example, consider the following HTML: |
| 29 | + |
| 30 | +```html |
| 31 | +<!DOCTYPE html> |
| 32 | +<html> |
| 33 | +<head> |
| 34 | + <title>Example with Attributes</title> |
| 35 | +</head> |
| 36 | +<body> |
| 37 | + <h1 class="header" id="main-title" data-info="example">Hello, World!</h1> |
| 38 | + <p>This is a paragraph.</p> |
| 39 | +</body> |
| 40 | +</html> |
| 41 | +``` |
| 42 | + |
| 43 | +For this document, the DOM tree would look like this: |
| 44 | + |
| 45 | +```graphql |
| 46 | +Document |
| 47 | + ├── html |
| 48 | + │ ├── head |
| 49 | + │ │ └── title |
| 50 | + │ │ └── "Example with Attributes" |
| 51 | + │ └── body |
| 52 | + │ ├── h1 |
| 53 | + │ │ ├── @class="header" |
| 54 | + │ │ ├── @id="main-title" |
| 55 | + │ │ ├── @data-info="example" |
| 56 | + │ │ └── "Hello, World!" |
| 57 | + │ └── p |
| 58 | + │ └── "This is a paragraph." |
| 59 | +``` |
| 60 | + |
| 61 | +The DOM plays a central role in web development by enabling developers to create dynamic and interactive web pages. |
| 62 | + |
| 63 | +- Access and manipulate elements: Developers can use JavaScript to select, modify, and create HTML elements. |
| 64 | + |
| 65 | +- Handle events: The DOM allows developers to listen for and respond to user events, such as clicks, keypresses, and form submissions. |
| 66 | + |
| 67 | +- Modify styles: Through the DOM, developers can change the CSS styles of elements dynamically. |
| 68 | + |
| 69 | +## 2. DOM Manipulation |
| 70 | + |
| 71 | +### 2.1. Accessing Elements |
| 72 | + |
| 73 | +- To get an element by its ID in JavaScript, you can use the `getElementById` method. |
| 74 | + |
| 75 | +```html |
| 76 | +<div id="title">Hello, World!</div> |
| 77 | +``` |
| 78 | + |
| 79 | + |
| 80 | +```js |
| 81 | +// Get the element with the ID 'myElement' |
| 82 | +const element = document.getElementById('myElement'); |
| 83 | + |
| 84 | +// Log the element to the console |
| 85 | +console.log(element); |
| 86 | +``` |
| 87 | + |
| 88 | +- To get elements by their class, we can use the `getElementsByClassName` method. This method returns a live HTMLCollection of elements with the specified class name. |
| 89 | + |
| 90 | +```html |
| 91 | +<div class="myClass">First Element</div> |
| 92 | +<div class="myClass">Second Element</div> |
| 93 | +<div class="myClass">Third Element</div> |
| 94 | +``` |
| 95 | + |
| 96 | +```js |
| 97 | +// Get the elements with the class name 'myClass' |
| 98 | +const elements = document.getElementsByClassName('myClass'); |
| 99 | + |
| 100 | +// Log the elements to the console |
| 101 | +console.log(elements); |
| 102 | + |
| 103 | +// Optionally, you can iterate over the elements as well |
| 104 | +for (let i = 0; i < elements.length; i++) { |
| 105 | + console.log(elements[i]) |
| 106 | +} |
| 107 | +``` |
| 108 | + |
| 109 | +- To get elements by tag name in the Document Object Model (DOM), we can use the `getElementsByTagName` method. This method allows you to retrieve a collection of elements that match a specified tag name. |
| 110 | + |
| 111 | +```html |
| 112 | +<h1>Hello, World!</h1> |
| 113 | +<p>This is a paragraph.</p> |
| 114 | +<div> |
| 115 | + <p>Another paragraph inside a div.</p> |
| 116 | + <p>Second paragraph inside a div.</p> |
| 117 | +</div> |
| 118 | +``` |
| 119 | + |
| 120 | +```js |
| 121 | +// Get all <p> elements in the document |
| 122 | +const paragraphs = document.getElementsByTagName("p"); |
| 123 | + |
| 124 | +// Loop through and log the text content of each <p> element |
| 125 | +for (let i = 0; i < paragraphs.length; i++) { |
| 126 | + console.log(paragraphs[i].textContent); |
| 127 | +} |
| 128 | +``` |
| 129 | + |
| 130 | +- The `querySelector` method in JavaScript allows you to select and retrieve the first element that matches a specified CSS selector within the document or within a specific element, |
| 131 | + |
| 132 | +```js |
| 133 | +// Select the first <p> element in the document |
| 134 | +const firstParagraph = document.querySelector("p"); |
| 135 | + |
| 136 | +// Select the element with id="main-title" |
| 137 | +const titleElement = document.querySelector("#main-title"); |
| 138 | + |
| 139 | +// Select the first element with class="intro" |
| 140 | +const introParagraph = document.querySelector(".intro"); |
| 141 | + |
| 142 | +// Select the first <p> element inside the <div> |
| 143 | +const paragraphInDiv = document.querySelector("div p"); |
| 144 | +``` |
| 145 | + |
| 146 | +- The `querySelectorAll` method in JavaScript allows you to select and retrieve a list (or NodeList) of all elements that match a specified CSS selector within the document or within a specific element. Unlike `querySelector`, which returns only the first matching element, `querySelectorAll` returns a NodeList containing all matching elements. |
| 147 | + |
| 148 | +```js |
| 149 | + |
| 150 | +// Select all <p> elements in the document |
| 151 | +const paragraphs = document.querySelectorAll("p"); |
| 152 | + |
| 153 | +// Log the number of <p> elements found |
| 154 | +console.log("Number of <p> elements:", paragraphs.length); |
| 155 | + |
| 156 | +// Select all elements with class="intro" |
| 157 | +const introElements = document.querySelectorAll(".intro"); |
| 158 | + |
| 159 | +// Select all <li> elements inside the <ul> |
| 160 | +const listItems = document.querySelectorAll("ul li"); |
| 161 | + |
| 162 | +``` |
| 163 | +### 2.2. Modifying Content |
| 164 | + |
| 165 | +- `innerHTML` allows you to get or set the HTML markup inside an element. |
| 166 | + |
| 167 | +```js |
| 168 | +// HTML element |
| 169 | +const divElement = document.getElementById("myDiv"); |
| 170 | + |
| 171 | +// Get inner HTML content of divElement |
| 172 | +const htmlContent = divElement.innerHTML; |
| 173 | +console.log("Inner HTML:", htmlContent); |
| 174 | + |
| 175 | +// Set inner HTML content of divElement |
| 176 | +divElement.innerHTML = "<p>New content with <strong>bold</strong> text.</p>"; |
| 177 | +``` |
| 178 | + |
| 179 | +- `textContent` allows you to get or set the text content inside an element. |
| 180 | + |
| 181 | +```js |
| 182 | +// HTML element |
| 183 | +const paragraphElement = document.getElementById("myParagraph"); |
| 184 | + |
| 185 | +// Get text content |
| 186 | +const textContent = paragraphElement.textContent; |
| 187 | +console.log("Text content:", textContent); |
| 188 | + |
| 189 | +// Set text content |
| 190 | +paragraphElement.textContent = "Updated text content."; |
| 191 | +``` |
| 192 | + |
| 193 | +- `innerText` allows you to get or set the visible text content inside an element. |
| 194 | + |
| 195 | +```js |
| 196 | +// HTML element |
| 197 | +const spanElement = document.getElementById("mySpan"); |
| 198 | + |
| 199 | +// Get inner text |
| 200 | +// Retrieves the visible text content inside an element, excluding hidden elements or elements with CSS display: none. |
| 201 | +const innerText = spanElement.innerText; |
| 202 | +console.log("Inner text:", innerText); |
| 203 | + |
| 204 | +// Set inner text |
| 205 | +spanElement.innerText = "Updated inner text."; |
| 206 | +``` |
| 207 | + |
| 208 | +### 2.3. Modifying Attributes |
| 209 | + |
| 210 | +- Use `getAttribute()` to get the value of an attribute. |
| 211 | +- Use `setAttribute()` to set a new value for an attribute. |
| 212 | +- Use `removeAttribute()` to remove an attribute. |
| 213 | + |
| 214 | +```html |
| 215 | +<div class="myClass">First Element</div> |
| 216 | +``` |
| 217 | + |
| 218 | +```js |
| 219 | +// Get the element with the ID 'myElement' |
| 220 | +const element = document.getElementById('myElement'); |
| 221 | + |
| 222 | +// Get the value of an attribute |
| 223 | +const classValue = element.getAttribute('class'); |
| 224 | +console.log('Class:', classValue); // Output: Class: myClass |
| 225 | + |
| 226 | +// Set a new value for an attribute |
| 227 | +element.setAttribute('class', 'newClass'); |
| 228 | +console.log('Updated Class:', element.getAttribute('class')); // Output: Updated Class: newClass |
| 229 | + |
| 230 | +// Remove an attribute |
| 231 | +element.removeAttribute('class'); |
| 232 | +console.log(element.hasAttribute('class')); // Output: false |
| 233 | +``` |
| 234 | + |
| 235 | +### 2.4. Creating and Inserting Elements |
| 236 | + |
| 237 | +- `createElement()` method creates a new HTML element. |
| 238 | +- `appendChild()` method appends a node as the last child of a parent node. |
| 239 | +- `insertBefore()` method inserts a node before an existing element within a a specified parent node. |
| 240 | +- `append()` method appends node to the end of a parent node. |
| 241 | +- `prepend()` method inserts node to the beginning of a parent node. |
| 242 | + |
| 243 | +```html |
| 244 | +<body> |
| 245 | + <div id="container"> |
| 246 | + <ul class="todo-list"></ul> |
| 247 | + <div> |
| 248 | +</body> |
| 249 | +``` |
| 250 | + |
| 251 | +```js |
| 252 | +const container = document.getElementById('container'); |
| 253 | +const todolist = document.querySelector('.todo-list'); |
| 254 | + |
| 255 | +// Create a new element |
| 256 | +const newToDo = document.createElement('li'); |
| 257 | +newToDo.setAttribute("class", "todo-item") |
| 258 | +newToDo.textContent = 'Buy fruits.'; |
| 259 | + |
| 260 | +// Append the new element as the last child |
| 261 | +todolist.appendChild(newToDo); |
| 262 | + |
| 263 | +// Create another new element |
| 264 | +const title = document.createElement('h2'); |
| 265 | +newToDo.textContent = 'My tasks'; |
| 266 | + |
| 267 | +// Insert the title before the list |
| 268 | +container.insertBefore(title, todolist); |
| 269 | + |
| 270 | +// Create yet another new element |
| 271 | +const lastElement = document.createElement('div'); |
| 272 | +lastElement.textContent = 'Last Element'; |
| 273 | + |
| 274 | +// Append yet another element as the last child |
| 275 | +container.append(lastElement); |
| 276 | + |
| 277 | +// Create and prepend a new element |
| 278 | +const firstElement = document.createElement('div'); |
| 279 | +firstElement.textContent = 'First Element'; |
| 280 | + |
| 281 | +// Prepend the new element as the first child |
| 282 | +container.prepend(firstElement); |
| 283 | +``` |
| 284 | + |
| 285 | +### 2.5. Removing Elements |
| 286 | + |
| 287 | +- `removeChild()` method removes a specified child node from the parent node. The removed child node is returned. |
| 288 | + |
| 289 | +- `remove()` method removes the element from the DOM. |
| 290 | + |
| 291 | +```html |
| 292 | +<div id="container"> |
| 293 | + <div id="childElement">Child Element</div> |
| 294 | + <div id="anotherChildElement">Another Child Element</div> |
| 295 | +</div> |
| 296 | +``` |
| 297 | + |
| 298 | +```js |
| 299 | +// Get the container element |
| 300 | +const container = document.getElementById('container'); |
| 301 | + |
| 302 | +// Get the child element to be removed |
| 303 | +const childElement = document.getElementById('childElement'); |
| 304 | + |
| 305 | +// Remove the child element using removeChild |
| 306 | +container.removeChild(childElement); |
| 307 | + |
| 308 | +// Get another child element to be removed |
| 309 | +const anotherChildElement = document.getElementById('anotherChildElement'); |
| 310 | + |
| 311 | +// Remove the element using remove() |
| 312 | +anotherChildElement.remove(); |
| 313 | + |
| 314 | +``` |
| 315 | +### 2.6. Modifying Styles |
| 316 | + |
| 317 | +- The `style` property allows to set or get inline styles for an element. This directly modifies the style attribute of the element in the DOM. |
| 318 | + |
| 319 | +```html |
| 320 | +<div id="myElement">Hello world!</div> |
| 321 | +``` |
| 322 | + |
| 323 | +```js |
| 324 | +// Get the element |
| 325 | +const element = document.getElementById('myElement'); |
| 326 | + |
| 327 | +// Change the background color and font size using the style property |
| 328 | +element.style.backgroundColor = 'blue'; |
| 329 | +element.style.fontSize = '20px'; |
| 330 | +``` |
| 331 | + |
| 332 | +- The `classList` property provides methods to add, remove, and toggle CSS classes on an element. This is a more flexible way to manage an element's classes compared to directly setting the `class` attribute. |
| 333 | + |
| 334 | +```js |
| 335 | +// Get the element |
| 336 | +const element = document.getElementById('myElement'); |
| 337 | + |
| 338 | +// Add a new class to the element |
| 339 | +element.classList.add('newClass'); |
| 340 | + |
| 341 | +// Remove an existing class from the element |
| 342 | +element.classList.remove('initialClass'); |
| 343 | + |
| 344 | +// Toggle a class on the element (add it if it doesn't exist, remove it if it does) |
| 345 | +element.classList.toggle('toggledClass'); |
| 346 | +``` |
| 347 | + |
| 348 | +### 2.7. Event Handling |
| 349 | + |
| 350 | +- The `addEventListener()` method attaches an event handler to an element. It allows multiple event listeners to be added to a single element for the same event type. |
| 351 | + |
| 352 | +```html |
| 353 | +<button id="myButton">Click Me</button> |
| 354 | +``` |
| 355 | + |
| 356 | +```js |
| 357 | +// Define the event handler function |
| 358 | +function handleClick() { |
| 359 | + alert('Button was clicked!'); |
| 360 | +} |
| 361 | + |
| 362 | +// Get the button element |
| 363 | +const button = document.getElementById('myButton'); |
| 364 | + |
| 365 | +// Add a click event listener |
| 366 | +button.addEventListener('click', handleClick); |
| 367 | +``` |
| 368 | + |
| 369 | +- The `removeEventListener()` method removes an event handler that was added with `addEventListener()`. |
| 370 | + |
| 371 | +```js |
| 372 | +button.removeEventListener('click', handleClick); |
| 373 | +``` |
| 374 | + |
| 375 | +## Conclusion |
| 376 | + |
| 377 | +Mastering DOM manipulation is crucial for creating dynamic, interactive web pages. The ability to access, modify, and interact with the DOM using JavaScript allows developers to build responsive and engaging user experiences. |
| 378 | + |
| 379 | +- **Understanding the DOM**: By understanding the structure and representation of a web document through the DOM, developers can effectively interact with and manipulate web pages. |
| 380 | + |
| 381 | +- **Accessing Elements**: Methods like `getElementById()`, `getElementsByClassName()`, `getElementsByTagName()`, `querySelector()`, and `querySelectorAll()` enable precise selection of elements within the DOM, facilitating targeted manipulations. |
| 382 | + |
| 383 | +- **Modifying Content and Attributes**: Techniques such as using `innerHTML`, `textContent`, and `innerText` for content modification, alongside `getAttribute()`, `setAttribute()`, and `removeAttribute()` for attribute management, provide powerful ways to dynamically change the document's content and properties. |
| 384 | + |
| 385 | +- **Creating and Inserting Elements**: Methods like `createElement()`, `appendChild()`, `insertBefore()`, `append()`, and `prepend()` allow developers to construct and integrate new elements into the DOM, enabling the dynamic construction of web pages. |
| 386 | + |
| 387 | +- **Removing Elements**: Using `removeChild()` and `remove()` methods facilitates the removal of elements from the DOM, which is essential for maintaining clean and efficient document structures. |
| 388 | + |
| 389 | +- **Modifying Styles**: Direct manipulation of inline styles via the `style` property and managing classes with classList methods (`add()`, `remove()`, `toggle()`) offer flexible control over the appearance and styling of elements. |
| 390 | + |
| 391 | +- **Event Handling**: The ability to attach and remove event listeners using `addEventListener()` and `removeEventListener()` empowers developers to create interactive elements that respond to user actions, enhancing the user experience. |
| 392 | + |
| 393 | +By leveraging these DOM manipulation techniques, developers can create rich, interactive web applications that provide a seamless and dynamic user experience. Understanding and utilizing these tools effectively is key to modern web development. |
0 commit comments