{"id":5772,"date":"2025-05-15T21:32:28","date_gmt":"2025-05-15T21:32:28","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=5772"},"modified":"2025-05-15T21:32:28","modified_gmt":"2025-05-15T21:32:28","slug":"dom-manipulation-in-vanilla-javascript-3","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/dom-manipulation-in-vanilla-javascript-3\/","title":{"rendered":"DOM Manipulation in Vanilla JavaScript"},"content":{"rendered":"<h1>DOM Manipulation in Vanilla JavaScript: A Comprehensive Guide<\/h1>\n<p>The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects and allows developers to manipulate the elements, attributes, and styles of a web page. In this blog, we will dive deep into DOM manipulation using Vanilla JavaScript, discussing concepts, methods, and practical examples to enhance your development skills.<\/p>\n<h2>What is the DOM?<\/h2>\n<p>The DOM is an essential concept in web development. When you load a web page, the browser creates a DOM tree based on the HTML document. Each node in this tree corresponds to a part of the document, such as elements, attributes, and text nodes. With DOM manipulation, you can dynamically change the content, structure, and style of your web pages without needing to reload them.<\/p>\n<h2>Accessing the DOM<\/h2>\n<p>Before manipulating elements, you must first access them through the DOM. There are several methods in JavaScript to accomplish this:<\/p>\n<h3>Using getElementById<\/h3>\n<p>The <strong>getElementById<\/strong> method retrieves an element by its unique ID.<\/p>\n<pre><code>\nconst myElement = document.getElementById('myId');\nconsole.log(myElement);\n<\/code><\/pre>\n<h3>Using getElementsByClassName<\/h3>\n<p>The <strong>getElementsByClassName<\/strong> method fetches elements by their class name. Note that it returns a live HTMLCollection.<\/p>\n<pre><code>\nconst elements = document.getElementsByClassName('myClass');\nconsole.log(elements);\n<\/code><\/pre>\n<h3>Using getElementsByTagName<\/h3>\n<p>This method allows you to select elements by their tag name.<\/p>\n<pre><code>\nconst divElements = document.getElementsByTagName('div');\nconsole.log(divElements);\n<\/code><\/pre>\n<h3>Using querySelector and querySelectorAll<\/h3>\n<p>The <strong>querySelector<\/strong> method returns the first element that matches a specified CSS selector, while <strong>querySelectorAll<\/strong> returns all matching elements as a NodeList.<\/p>\n<pre><code>\n\/\/ Selects the first element with the class name 'myClass'\nconst firstElement = document.querySelector('.myClass');\n\n\/\/ Selects all elements with the class name 'myClass'\nconst allElements = document.querySelectorAll('.myClass');\n\nconsole.log(firstElement);\nconsole.log(allElements);\n<\/code><\/pre>\n<h2>Modifying the DOM<\/h2>\n<p>Once you have access to the DOM elements, you can modify them in various ways, including changing their content, styles, and attributes.<\/p>\n<h3>Changing Text Content<\/h3>\n<p>You can change the text content of an element with the <strong>textContent<\/strong> or <strong>innerHTML<\/strong> property.<\/p>\n<pre><code>\n\/\/ Changing text using textContent\nconst myHeading = document.getElementById('myHeading');\nmyHeading.textContent = 'Hello, World!';\n\n\/\/ Changing HTML content\nconst myDiv = document.getElementById('myDiv');\nmyDiv.innerHTML = '<strong>This is bold text!<\/strong>';\n<\/code><\/pre>\n<h3>Updating Styles<\/h3>\n<p>To change an element&#8217;s CSS styles, you can use the <strong>style<\/strong> property.<\/p>\n<pre><code>\nconst myElement = document.getElementById('myElement');\nmyElement.style.color = 'blue';\nmyElement.style.backgroundColor = 'yellow';\n<\/code><\/pre>\n<h3>Adding and Removing Classes<\/h3>\n<p>Use the <strong>classList<\/strong> property to manage classes. It allows you to add, remove, and toggle classes easily.<\/p>\n<pre><code>\nconst myElement = document.getElementById('myElement');\nmyElement.classList.add('newClass'); \/\/ Adds a class\nmyElement.classList.remove('oldClass'); \/\/ Removes a class\nmyElement.classList.toggle('active'); \/\/ Toggles a class\n<\/code><\/pre>\n<h3>Creating and Inserting Elements<\/h3>\n<p>You can create new elements and insert them into the DOM using the following methods:<\/p>\n<pre><code>\n\/\/ Creating a new element\nconst newElement = document.createElement('p');\nnewElement.textContent = 'This is a new paragraph.';\n\n\/\/ Inserting the new element\nconst myDiv = document.getElementById('myDiv');\nmyDiv.appendChild(newElement); \/\/ Adds as the last child\nmyDiv.insertBefore(newElement, myDiv.firstChild); \/\/ Adds as the first child\n<\/code><\/pre>\n<h3>Removing Elements<\/h3>\n<p>To remove an element from the DOM, you can use the <strong>remove<\/strong> method or the <strong>removeChild<\/strong> method of its parent element.<\/p>\n<pre><code>\nconst myElement = document.getElementById('myElement');\nmyElement.remove(); \/\/ Removes the element itself\n\n\/\/ OR\n\nconst parent = myElement.parentNode;\nparent.removeChild(myElement); \/\/ Removes the element through its parent\n<\/code><\/pre>\n<h2>Event Handling<\/h2>\n<p>Events are essential for interaction in a web application. DOM manipulation allows you to respond to user actions through events.<\/p>\n<h3>Adding Event Listeners<\/h3>\n<p>You can add event listeners to elements using the <strong>addEventListener<\/strong> method.<\/p>\n<pre><code>\nconst button = document.getElementById('myButton');\nbutton.addEventListener('click', function() {\n    alert('Button clicked!');\n});\n<\/code><\/pre>\n<h3>Removing Event Listeners<\/h3>\n<p>To remove an event listener, you must provide a reference to the same function that was used to add it.<\/p>\n<pre><code>\nfunction handleClick() {\n    alert('Button clicked!');\n}\n\nconst button = document.getElementById('myButton');\nbutton.addEventListener('click', handleClick);\n\n\/\/ Later, to remove:\nbutton.removeEventListener('click', handleClick);\n<\/code><\/pre>\n<h2>Best Practices for DOM Manipulation<\/h2>\n<p>When working with the DOM, consider these best practices to ensure efficient and clean code:<\/p>\n<ul>\n<li><strong>Minimize reflows and repaints:<\/strong> Batch DOM updates together to prevent multiple layout calculations.<\/li>\n<li><strong>Use Document Fragments:<\/strong> When adding multiple elements, create a Document Fragment to minimize DOM reflows.<\/li>\n<li><strong>Detach and Re-append:<\/strong> If you need to manipulate an element extensively, detach it from the DOM, manipulate, and then re-append it.<\/li>\n<li><strong>Cache references:<\/strong> Store references to frequently accessed DOM elements to improve performance.<\/li>\n<\/ul>\n<h2>Conclusion<\/h2>\n<p>DOM manipulation in Vanilla JavaScript is a powerful skill for any web developer. It allows you to create dynamic, interactive user experiences by changing the structure and content of HTML documents on the fly. With the methods and best practices discussed in this blog, you&#8217;re well-equipped to enhance your web applications. Remember, while libraries like jQuery can simplify DOM manipulation, understanding Vanilla JavaScript provides a solid foundation for your front-end development journey.<\/p>\n<p>Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>DOM Manipulation in Vanilla JavaScript: A Comprehensive Guide The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects and allows developers to manipulate the elements, attributes, and styles of a web page. In this blog, we will dive deep into DOM<\/p>\n","protected":false},"author":90,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[172],"tags":[330],"class_list":["post-5772","post","type-post","status-publish","format-standard","category-javascript","tag-javascript"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5772","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/90"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=5772"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5772\/revisions"}],"predecessor-version":[{"id":5773,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5772\/revisions\/5773"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=5772"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=5772"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=5772"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}