{"id":5746,"date":"2025-05-14T19:32:34","date_gmt":"2025-05-14T19:32:34","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=5746"},"modified":"2025-05-14T19:32:34","modified_gmt":"2025-05-14T19:32:34","slug":"dom-manipulation-in-vanilla-javascript-2","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/dom-manipulation-in-vanilla-javascript-2\/","title":{"rendered":"DOM Manipulation in Vanilla JavaScript"},"content":{"rendered":"<h1>DOM Manipulation in Vanilla JavaScript<\/h1>\n<p>The Document Object Model (DOM) is a programming interface provided by the web browsers that allows scripts to update the content, structure, and style of a document. Manipulating the DOM is a crucial skill for any web developer since it allows for dynamic and interactive web applications. In this article, we will dive into the essentials of DOM manipulation using vanilla JavaScript, explore its methods, and discuss best practices with practical examples.<\/p>\n<h2>Understanding the DOM<\/h2>\n<p>The DOM represents the document as a tree structure where each node is an object representing a part of the document. A node can be an element, an attribute, or even text. For instance, an HTML document is represented as a hierarchy of nodes, where the document itself is the root node.<\/p>\n<p>Here&#8217;s a simple structure of a DOM:<\/p>\n<pre>\ndocument\n \u2514\u2500\u2500 html\n     \u251c\u2500\u2500 head\n     \u2502   \u2514\u2500\u2500 title\n     \u2514\u2500\u2500 body\n         \u251c\u2500\u2500 h1\n         \u251c\u2500\u2500 p\n         \u2514\u2500\u2500 div\n<\/pre>\n<h2>Accessing DOM Elements<\/h2>\n<p>Before we can manipulate the DOM, we need to access its elements. There are several methods available in JavaScript to do this:<\/p>\n<h3>1. getElementById<\/h3>\n<p>This method is used to select an element by its unique ID.<\/p>\n<pre>\nconst header = document.getElementById('header');\n<\/pre>\n<h3>2. getElementsByClassName<\/h3>\n<p>This method returns a collection of elements with the specified class name.<\/p>\n<pre>\nconst items = document.getElementsByClassName('item');\n<\/pre>\n<h3>3. getElementsByTagName<\/h3>\n<p>This method retrieves a live HTMLCollection of elements with the specified tag name.<\/p>\n<pre>\nconst paragraphs = document.getElementsByTagName('p');\n<\/pre>\n<h3>4. querySelector<\/h3>\n<p>The <code>querySelector<\/code> method returns the first element that matches a specified CSS selector.<\/p>\n<pre>\nconst firstItem = document.querySelector('.item');\n<\/pre>\n<h3>5. querySelectorAll<\/h3>\n<p>This method returns all elements that match the specified CSS selector, in the form of a static NodeList.<\/p>\n<pre>\nconst allItems = document.querySelectorAll('.item');\n<\/pre>\n<h2>Modifying DOM Elements<\/h2>\n<p>Once you&#8217;ve successfully accessed an element, you can modify its attributes, styles, and content.<\/p>\n<h3>Changing Text Content<\/h3>\n<p>The <code>textContent<\/code> property allows you to change the text within an element.<\/p>\n<pre>\nconst header = document.getElementById('header');\nheader.textContent = 'Welcome to My Website';\n<\/pre>\n<h3>Changing HTML Content<\/h3>\n<p>If you need to set HTML content inside an element, you can use the <code>innerHTML<\/code> property.<\/p>\n<pre>\nconst description = document.getElementById('description');\ndescription.innerHTML = '<strong>This text is bold!<\/strong>';\n<\/pre>\n<h3>Modifying Attributes<\/h3>\n<p>To manipulate an element&#8217;s attributes, such as <code>src<\/code> for images or <code>href<\/code> for links, use the <code>setAttribute<\/code> method.<\/p>\n<pre>\nconst image = document.getElementById('myImage');\nimage.setAttribute('src', 'newImage.jpg');\n<\/pre>\n<h3>Changing Styles<\/h3>\n<p>You can modify an element&#8217;s CSS styles directly through the <code>style<\/code> property.<\/p>\n<pre>\nconst button = document.getElementById('myButton');\nbutton.style.backgroundColor = 'blue';\nbutton.style.color = 'white';\n<\/pre>\n<h2>Creating and Removing DOM Elements<\/h2>\n<p>Dynamically creating new elements and removing existing ones is also a significant part of DOM manipulation.<\/p>\n<h3>Creating Elements<\/h3>\n<p>The <code>createElement<\/code> method creates a new element, while <code>appendChild<\/code> adds it to the desired parent.<\/p>\n<pre>\nconst newDiv = document.createElement('div');\nnewDiv.textContent = 'This is a new div!';\ndocument.body.appendChild(newDiv);\n<\/pre>\n<h3>Removing Elements<\/h3>\n<p>To remove an element, use the <code>removeChild<\/code> method on its parent node.<\/p>\n<pre>\nconst elementToRemove = document.getElementById('elementToRemove');\nelementToRemove.parentNode.removeChild(elementToRemove);\n<\/pre>\n<h2>Event Handling<\/h2>\n<p>Event handling is another essential part of DOM manipulation, allowing you to respond to user interactions such as clicks, key presses, and form submissions.<\/p>\n<h3>Adding Event Listeners<\/h3>\n<p>Use the <code>addEventListener<\/code> method to register an event listener for an element.<\/p>\n<pre>\nconst button = document.getElementById('myButton');\nbutton.addEventListener('click', function() {\n    alert('Button clicked!');\n});\n<\/pre>\n<h3>Removing Event Listeners<\/h3>\n<p>To prevent memory leaks, you can also remove event listeners using the <code>removeEventListener<\/code> method.<\/p>\n<pre>\nconst handleClick = function() {\n    alert('Button clicked!');\n};\nbutton.addEventListener('click', handleClick);\n\/\/ Later on...\nbutton.removeEventListener('click', handleClick);\n<\/pre>\n<h2>Best Practices for DOM Manipulation<\/h2>\n<p>When manipulating the DOM, following best practices can lead to better performance and cleaner code.<\/p>\n<h3>Minimize DOM Access<\/h3>\n<p>Accessing and manipulating the DOM can be slow, so cache your DOM queries instead of querying the same elements multiple times.<\/p>\n<pre>\nconst list = document.getElementById('list');\n\/\/ Modify the list items\nfor (let i = 0; i &lt; list.children.length; i++) {\n    list.children[i].style.color = &#039;red&#039;;\n}\n<\/pre>\n<h3>Batch DOM Changes<\/h3>\n<p>Whenever possible, batch your changes to minimize layout thrashing. Hide the element, make all changes, then show it again.<\/p>\n<pre>\nconst list = document.getElementById('list');\nlist.style.display = 'none';\n\/\/ Make changes\nlist.innerHTML = '<li>New Item<\/li>';\nlist.style.display = 'block';\n<\/pre>\n<h3>Use Document Fragments<\/h3>\n<p>When adding multiple elements, make use of a <code>DocumentFragment<\/code> for better performance.<\/p>\n<pre>\nconst fragment = document.createDocumentFragment();\nfor (let i = 0; i &lt; 10; i++) {\n    const newItem = document.createElement(&#039;li&#039;);\n    newItem.textContent = `Item ${i + 1}`;\n    fragment.appendChild(newItem);\n}\ndocument.getElementById(&#039;list&#039;).appendChild(fragment);\n<\/pre>\n<h2>Conclusion<\/h2>\n<p>Mastering DOM manipulation with vanilla JavaScript empowers you to create dynamic, interactive web applications. Understanding various ways to access, modify, create, and remove DOM elements is crucial for web development. By applying the best practices mentioned in this article, you can optimize your code performance and enhance user experience.<\/p>\n<p>As you continue your journey into web development, let this article serve as a reference for your DOM manipulation needs. Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>DOM Manipulation in Vanilla JavaScript The Document Object Model (DOM) is a programming interface provided by the web browsers that allows scripts to update the content, structure, and style of a document. Manipulating the DOM is a crucial skill for any web developer since it allows for dynamic and interactive web applications. In this article,<\/p>\n","protected":false},"author":77,"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-5746","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\/5746","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\/77"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=5746"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5746\/revisions"}],"predecessor-version":[{"id":5747,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/5746\/revisions\/5747"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=5746"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=5746"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=5746"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}