<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Document Object Model - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Document Object Model - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Mon, 25 May 2026 22:38:19 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/document-object-model/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Virtual DOM vs Shadow DOM – What's the Difference? ]]>
                </title>
                <description>
                    <![CDATA[ In web development, understanding the inner workings of the Document Object Model (DOM) is crucial. Two concepts that often come up in discussions about DOM are Virtual DOM and Shadow DOM. While they sound similar, they serve different purposes and h... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/virtual-dom-vs-shadow-dom/</link>
                <guid isPermaLink="false">66c4c417e486f65d4125b803</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Joan Ayebola ]]>
                </dc:creator>
                <pubDate>Mon, 18 Mar 2024 08:22:16 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/03/Ivory-and-Blue-Lavender-Aesthetic-Photo-Collage-Presentation--13-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In web development, understanding the inner workings of the Document Object Model (DOM) is crucial. Two concepts that often come up in discussions about DOM are Virtual DOM and Shadow DOM.</p>
<p>While they sound similar, they serve different purposes and have distinct characteristics. </p>
<p>In this comprehensive guide, we'll delve into the intricacies of Virtual DOM and Shadow DOM, highlighting their differences with simple explanations and illustrative code snippets.</p>
<h3 id="heading-table-of-contents">Table of Contents</h3>
<ol>
<li><strong><a class="post-section-overview" href="#heading-introduction-to-dom">Introduction to DOM</a></strong></li>
<li><strong><a class="post-section-overview" href="#heading-what-is-virtual-dom">What is Virtual DOM?</a></strong><br>– <a class="post-section-overview" href="#heading-how-virtual-dom-works">How Virtual DOM Works</a></li>
<li><a class="post-section-overview" href="#what-is-shallow-dom"><strong>What is Shadow DOM?</strong></a><br>– <a class="post-section-overview" href="#understanding-shallow-dom">Understanding Shadow DOM</a></li>
<li><a class="post-section-overview" href="#differences-between-virtual-dom-and-shallow-dom"><strong>Differences Between Virtual DOM and Shadow DOM</strong></a></li>
<li><strong><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></strong></li>
</ol>
<h2 id="heading-introduction-to-dom">Introduction to DOM</h2>
<p>Before we dive into Virtual DOM and Shadow DOM, let's briefly discuss what the Document Object Model (DOM) is. </p>
<p>The DOM represents the structure of an HTML document as a tree-like structure, where each node represents an element, attribute, or text within the document. JavaScript can manipulate the DOM dynamically, enabling developers to create interactive web pages.</p>
<h2 id="heading-what-is-virtual-dom">What is Virtual DOM?</h2>
<p>The Virtual DOM is a concept used by libraries like React to improve the performance of web applications. It's essentially a lightweight copy of the actual DOM, maintained by the framework. </p>
<p>When changes are made to the application state, React creates a new Virtual DOM representation and compares it with the previous one to identify the differences (known as "diffing"). Only the necessary changes are then applied to the real DOM, resulting in efficient updates.</p>
<h3 id="heading-how-virtual-dom-works">How Virtual DOM Works</h3>
<p>Let's consider a simple example to understand how Virtual DOM works in React:</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// Initial render</span>
<span class="hljs-keyword">const</span> element = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Hello, world!<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
ReactDOM.render(element, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>));

<span class="hljs-comment">// Update</span>
<span class="hljs-keyword">const</span> updatedElement = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>Hello, world! Updated.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>;
ReactDOM.render(updatedElement, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>));
</code></pre>
<p>In this example, React creates a Virtual DOM representation of the <code>element</code>. When an update occurs, it creates a new Virtual DOM representation of the <code>updatedElement</code>. </p>
<p>React then compares the two Virtual DOM representations to identify the difference (in this case, the text content change). Finally, React updates the real DOM with the necessary changes, resulting in an efficient update process.</p>
<h2 id="heading-what-is-shadow-dom">What is Shadow DOM?</h2>
<p>Shadow DOM is a term used to describe a limited or restricted view of the DOM tree. Unlike the Virtual DOM, which is a concept used to optimize performance, Shadow DOM refers to a specific structure within the DOM tree itself.</p>
<h3 id="heading-understanding-shadow-dom">Understanding Shadow DOM</h3>
<p>Consider a scenario where you have a custom web component encapsulated with Shadow DOM:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Shadow DOM Example<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">my-custom-element</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">my-custom-element</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyCustomElement</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HTMLElement</span> </span>{
      <span class="hljs-keyword">constructor</span>() {
        <span class="hljs-built_in">super</span>();
        <span class="hljs-keyword">const</span> shadow = <span class="hljs-built_in">this</span>.attachShadow({ <span class="hljs-attr">mode</span>: <span class="hljs-string">'open'</span> });
        <span class="hljs-keyword">const</span> span = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'span'</span>);
        span.textContent = <span class="hljs-string">'Hello, Shadow DOM!'</span>;
        shadow.appendChild(span);
      }
    }
    customElements.define(<span class="hljs-string">'my-custom-element'</span>, MyCustomElement);
  </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this example, we define a custom element <code>my-custom-element</code> that encapsulates its content within Shadow DOM using the <code>attachShadow</code> method. The content inside the shadow root is isolated from the rest of the document, creating a boundary known as the Shadow DOM.</p>
<h2 id="heading-differences-between-virtual-dom-and-shadow-dom">Differences Between Virtual DOM and Shadow DOM</h2>
<p>Now that you have a basic understanding of the Virtual DOM and Shadow DOM, let's compare them based on different aspects:</p>
<h3 id="heading-purpose">Purpose</h3>
<ul>
<li><strong>Virtual DOM</strong>: Primarily aimed at improving performance by minimizing the number of DOM manipulations required during updates.</li>
<li><strong>Shadow DOM</strong>: Focuses on encapsulating the style and behavior of web components, providing a scoped environment for CSS and JavaScript.</li>
</ul>
<h3 id="heading-implementation">Implementation</h3>
<ul>
<li><strong>Virtual DOM</strong>: Implemented by libraries/frameworks like React, Vue.js, and Angular to facilitate efficient updates of the real DOM.</li>
<li><strong>Shadow DOM</strong>: Implemented natively by web browsers to support encapsulation of web components with Shadow DOM.</li>
</ul>
<h3 id="heading-performance">Performance</h3>
<ul>
<li><strong>Virtual DOM</strong>: Offers performance benefits by reducing the number of DOM manipulations, resulting in faster updates and rendering.</li>
<li><strong>Shadow DOM</strong>: While Shadow DOM itself doesn't directly impact performance, it can enhance performance by isolating component styles and behavior.</li>
</ul>
<h3 id="heading-isolation">Isolation</h3>
<ul>
<li><strong>Virtual DOM</strong>: Doesn't provide isolation by itself but helps in minimizing unintended side effects of DOM updates through its efficient diffing algorithm.</li>
<li><strong>Shadow DOM</strong>: Provides encapsulation and isolation for the content of web components, preventing style and behavior leakage to the rest of the document.</li>
</ul>
<h3 id="heading-usage">Usage</h3>
<ul>
<li><strong>Virtual DOM</strong>: Commonly used in modern JavaScript frameworks like React, where components are re-rendered efficiently based on state changes.</li>
<li><strong>Shadow DOM</strong>: Utilized when creating custom web components with encapsulated styles and behavior, ensuring modularity and reusability.</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, both Virtual DOM and Shadow DOM play significant roles in web development, albeit in different contexts. While Virtual DOM focuses on optimizing DOM updates for performance, Shadow DOM provides encapsulation and isolation for web components, enhancing modularity and maintainability. </p>
<p>Understanding the differences between these concepts is crucial for building efficient and scalable web applications.</p>
<p>By leveraging Virtual DOM in frameworks like React and embracing Shadow DOM for encapsulating web components, developers can create robust and maintainable web applications that offer optimal performance and scalability. </p>
<p>As web technologies continue to evolve, having a solid understanding of these concepts will remain invaluable in web development.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript in the Browser – How the Document Object Model (DOM) and Events Work ]]>
                </title>
                <description>
                    <![CDATA[ In this in-depth tutorial, you'll learn all about the Document Object Model, or DOM for short. As a web developer, understanding the DOM is fundamental for interacting with web browsers and creating dynamic web applications.  Throughout this guide, w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-in-the-browser-dom-and-events/</link>
                <guid isPermaLink="false">66c7218887ceefbdaf9b921b</guid>
                
                    <category>
                        <![CDATA[ browser ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Thu, 15 Feb 2024 20:07:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/JavaScript-in-the-Browser-with-Photo-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this in-depth tutorial, you'll learn all about the Document Object Model, or DOM for short. As a web developer, understanding the DOM is fundamental for interacting with web browsers and creating dynamic web applications. </p>
<p>Throughout this guide, we will explore the DOM's hierarchical tree structure, essential properties, and methods for accessing and modifying nodes. We'll also dive into event handling and various techniques for efficient DOM manipulation.</p>
<p>By the end of this guide, you should be able to confidently manipulate the DOM to meet the demands of your web development projects.</p>
<h3 id="heading-prerequisites">Prerequisites:</h3>
<p>While this guide is designed to be beginner-friendly and accessible to anyone, having a basic understanding of JavaScript fundamentals will greatly enhance your ability to grasp the practical concepts covered. </p>
<p>Also, familiarity with HTML and CSS is a plus and will help you comprehend and apply the material we cover. </p>
<p>If you're new to JavaScript, consider familiarizing yourself with variables, data types, functions, loops, and basic DOM manipulation techniques before diving into this tutorial. This foundational knowledge will ensure a smoother learning experience as we explore more advanced topics related to the Document Object Model (DOM).</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#browser-object-model-bom-">What is the Browser Object Model (BOM)</a>?</li>
<li><a class="post-section-overview" href="#what-is-the-document-object-model-dom">What is the Document Object Model (DOM)?</a></li>
<li><a class="post-section-overview" href="#heading-dom-tree-structure">DOM Tree Structure</a><br>– <a class="post-section-overview" href="#heading-types-of-nodes-in-the-dom-tree">Types of Nodes in the DOM Tree</a><br>– <a class="post-section-overview" href="#heading-node-relationships">Node Relationships</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-dom-elements">How to Work with DOM Elements</a><br>– <a class="post-section-overview" href="#methods-for-traversing-the-dom-">Traversing the DOM</a><br>– <a class="post-section-overview" href="#heading-methods-for-querying-dom-elements">Methods for Querying DOM Elements</a><br>– <a class="post-section-overview" href="#heading-matches-closest-and-contains">Specialized Selectors (Matches, Closest, Contains)</a><br>– <a class="post-section-overview" href="#heading-how-to-inspect-dom-elements">How to Inspect DOM Elements</a><br>– <a class="post-section-overview" href="#heading-table-navigation-in-the-dom">Table Navigation in the DOM</a></li>
<li><a class="post-section-overview" href="#heading-how-to-modify-dom-elements">How to Modify DOM Elements</a><br>– <a class="post-section-overview" href="#heading-how-to-manipulate-element-content-and-visibility">How to Manipulate Element Content and Visibility</a><br>– <a class="post-section-overview" href="#heading-how-to-modify-element-attributes">How to Modify Element Attributes</a><br>– <a class="post-section-overview" href="#heading-html-insertion-methods">HTML Insertion Methods</a><br>– <a class="post-section-overview" href="#heading-how-to-manipulate-classes-with-javascript">How to Manipulate Classes with JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-event-handling-in-the-dom">Event Handling in the DOM</a><br>– <a class="post-section-overview" href="#heading-common-types-of-events">Common Types of Events</a><br>– <a class="post-section-overview" href="#heading-event-handlers">Event Handlers</a><br>– <a class="post-section-overview" href="#heading-event-propagation">Event Propagation</a><br>– <a class="post-section-overview" href="#heading-event-bubbling">Event Bubbling</a><br>– <a class="post-section-overview" href="#heading-event-delegation">Event Delegation</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-the-browser-object-model-bom">What is the Browser Object Model (BOM)?</h2>
<p>The Browser Object Model is like a set of tools provided by the browser itself. It's not part of the official DOM specification, but it's specific to web browsers. As a result, the objects and methods available in the BOM may vary between different browsers.</p>
<p>The BOM provides JavaScript access to browser-specific things like the browser's history, location, and browser window itself.</p>
<h3 id="heading-window-object">Window Object</h3>
<p>The <code>window</code> Object serves as a global object in the browser, representing the browser window and is the top-level object in JavaScript when we're working in a web browser. You can access it by typing <code>window</code> in the browser console:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>); <span class="hljs-comment">// prints the Window object</span>
</code></pre>
<p>Since, it's global, you can access it from anywhere and use it to access other global objects such as the console and the alert function.</p>
<p>The <code>window</code> object is a key part of the BOM and provides access to many browser-related things. For example, <code>window.location.href</code> gives you the URL of the current web page.</p>
<p>Functions like <code>alert()</code>, <code>prompt()</code>, and <code>confirm()</code> are also part of the BOM, allowing you to interact with users through pop-up dialogs.</p>
<h2 id="heading-what-is-the-document-object-model-dom">What is the Document Object Model (DOM)?</h2>
<p>The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a web page, allowing interaction with its elements using programming languages like JavaScript.</p>
<p>The DOM contains the <code>document</code> object, which represents the DOM structure of the current web page and has properties and methods that allow you to manipulate the DOM.</p>
<p>You can access the <code>document</code> object by typing <code>document</code> in the browser console:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>); <span class="hljs-comment">// prints the DOM object</span>
</code></pre>
<p>You use <code>document</code> object to access and manipulate different parts of the HTML document. Elements within the DOM can be accessed using properties and methods of this object.</p>
<p>Examples include accessing the <code>body</code> or <code>title</code> element, retrieving HTML content (<code>innerHTML</code>), accessing text content (<code>innerText</code>) and changing <code>styles</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Accessing the document's title</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.title);

<span class="hljs-comment">// Changing the document's title</span>
<span class="hljs-built_in">document</span>.title = <span class="hljs-string">"changed Title"</span>;

<span class="hljs-comment">// Accessing the document's body </span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body);
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Changing background color of body element using inline CSS</span>
<span class="hljs-built_in">document</span>.body.style.backgroundColor = <span class="hljs-string">"red"</span>;
</code></pre>
<p>You can use the DOM to interact with web pages dynamically. This allows JavaScript to access, modify, and manipulate the content, structure, and style of a web document in response to user actions or other events. </p>
<p>Let's illustrate the concept of DOM manipulation with a simple example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"message"</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"changeText"</span>&gt;</span>Change Text<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-comment">// we select the paragraph element by its ID</span>
      <span class="hljs-keyword">let</span> messageElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"message"</span>);

      <span class="hljs-comment">// let's add event listener to button element using ID</span>
      <span class="hljs-built_in">document</span>
        .getElementById(<span class="hljs-string">"changeText"</span>)
        .addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
          <span class="hljs-comment">// this  will change the text content of the paragraph element</span>
          messageElement.textContent = <span class="hljs-string">"Text Changed!"</span>;
        });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this example, we have an HTML document with a <code>&lt;div&gt;</code> container containing a <code>&lt;p&gt;</code> element and a <code>&lt;button&gt;</code> element. </p>
<p>Using JavaScript, we can select the <code>&lt;p&gt;</code> element by its ID and attach an event listener to the <code>&lt;button&gt;</code> element. When the button is clicked, the text content of the paragraph element is changed dynamically.</p>
<h2 id="heading-dom-tree-structure">DOM Tree Structure</h2>
<p>The DOM represents the layout of HTML and XML documents as a tree-like structure, resembling the hierarchical arrangement of elements on a web page. In this tree, each node represents a part of the document, such as HTML elements, attributes, and text.</p>
<p>The top-level node in the tree is called the <strong>document node</strong>, which represents the entire HTML document. From there, it branches out to include all elements and their relationships within the document. Here's a visual representation of that:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/pic_htmltree-1.gif" alt="Image" width="600" height="400" loading="lazy">
<em>DOM Tree of Objects</em></p>
<h3 id="heading-types-of-nodes-in-the-dom-tree">Types of Nodes in the DOM Tree</h3>
<p>There are two main types of nodes in the DOM:</p>
<ol>
<li><strong>Element Nodes:</strong> Represent HTML elements such as <code>&lt;div&gt;</code>, <code>&lt;h1&gt;</code>, <code>&lt;p&gt;</code>, <code>&lt;span&gt;</code>, and so on. These nodes make up the backbone of the DOM tree and form the structure of the HTML document.</li>
<li><strong>Text Nodes:</strong> Represent text content within HTML elements. Text always serves as the last child (leaf node) of an element node and cannot contain any child nodes.</li>
</ol>
<p>In HTML, whitespace such as spaces, tabs, and line breaks are considered part of the text content within HTML elements and are represented as <strong>text nodes</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-62.png" alt="Image" width="600" height="400" loading="lazy">
<em>Linebreak is 1st child node, div (Blue) is 2nd, linebreak again 3rd</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-64.png" alt="Image" width="600" height="400" loading="lazy">
<em>We can see all the nodes here including non-element ones (like text nodes or comment nodes)</em></p>
<p>We also have:</p>
<ul>
<li><strong>Attribute Nodes:</strong> Represent attributes of HTML elements, for example <code>id</code>, <code>class</code>, <code>src</code>, <code>href</code>, and so on.</li>
<li><strong>Comment Nodes:</strong> Nodes representing comments within the HTML markup.</li>
</ul>
<p>To access and manipulate DOM elements, we can "walk" through the tree structure using JavaScript. For instance:</p>
<ul>
<li><code>document.head</code>: Selects the <code>&lt;head&gt;</code> element of the current HTML document.</li>
<li><code>document.body</code>: Selects the <code>&lt;body&gt;</code> element of the current HTML document.</li>
<li><code>document.documentElement</code>: Selects the root element of the DOM tree, that is <code>&lt;html&gt;</code>.</li>
</ul>
<p>Once we access an element, we can modify its attributes or properties accordingly. For example, we can alter the background color of the <code>&lt;body&gt;</code> element to red by executing <code>document.body.style.backgroundColor = "red"</code> in the console.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-80.png" alt="Image" width="600" height="400" loading="lazy">
<em>We can see the body color has changed to "red"</em></p>
<h3 id="heading-node-relationships">Node Relationships</h3>
<p>Nodes in the DOM tree have parent-child relationships, which form the hierarchical structure of the tree. A child is an element that directly resides within another element (the parent).</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>In the DOM tree, sibling elements are arranged linearly. The element to the right of the current element is called the next sibling, while the element to the left is called the previous sibling.</p>
<p>In the above example, the <code>&lt;p&gt;</code> element (previous sibling of ) and the <code>&lt;button&gt;</code> element (next sibling of </p><p>) are <strong>sibling nodes</strong> as they share the same parent. They are both <strong>children nodes</strong> of the <code>&lt;div&gt;</code> element with the ID "container". So the <code>&lt;div&gt;</code> element serves as the <strong>parent node</strong> of both the <code>&lt;p&gt;</code> and <code>&lt;button&gt;</code> elements.</p>
<p>Elements positioned above a given element in the DOM tree hierarchy are called ancestors. In the given code, the <code>&lt;html&gt;</code> element acts as the <strong>ancestor</strong> of the <code>&lt;body&gt;</code>, <code>&lt;h1&gt;</code>, and <code>&lt;p&gt;</code> elements, and they are <strong>descendants</strong> of the <code>&lt;html&gt;</code> element.</p>
<h2 id="heading-how-to-work-with-dom-elements">How to Work with DOM Elements</h2>
<p>Now, let's dive into accessing nodes in the DOM using various properties and methods.</p>
<h3 id="heading-traversing-the-dom">Traversing the DOM:</h3>
<p>When working with the Document Object Model (DOM), it's important to understand the distinction between element nodes (HTML elements) and non-element nodes (like text nodes, comments, and so on). Certain properties and methods specifically deal with either element nodes or all types of nodes, including non-element nodes.</p>
<p><strong>NodeList vs. HTMLCollection:</strong> Different properties return different collections of nodes. NodeList contains all types of nodes, while HTMLCollection specifically holds element nodes. Understanding this distinction is crucial for interpreting the results.</p>
<p><strong>Properties for All Nodes (Including Non-element Nodes):</strong> These properties return nodes of all types, including element nodes, text nodes, and comment nodes. </p>
<p><code>childNodes</code> returns a NodeList containing all child nodes and the <code>parentNode</code> property returns the parent node of the specified node. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Access the first child of the body node</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body.childNodes[<span class="hljs-number">0</span>]);


<span class="hljs-comment">// parentnode; the parent of a &lt;p&gt; element within a &lt;div&gt; would be the &lt;div&gt; itself.</span>
<span class="hljs-keyword">let</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>); <span class="hljs-comment">// Select the &lt;p&gt; element</span>
<span class="hljs-built_in">console</span>.log(p.parentNode); <span class="hljs-comment">// Output: &lt;div&gt; element (parent of p);</span>
</code></pre>
<p>Spaces between tags and line returns in HTML code are considered text nodes by the browser. So, the actual first child node might not be what you expect.</p>
<p><code>firstChild</code>/<code>lastChild</code>: Returns the first/last child node, again including all types.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.body.firstChild; <span class="hljs-comment">// Outputs: First child node (likely a linebreak(text node))</span>
<span class="hljs-built_in">document</span>.body.lastChild; <span class="hljs-comment">// Outputs: Last child node (likely a script tag)</span>
</code></pre>
<p>So we can say the following:</p>
<pre><code class="lang-javascript">element.childNodes[<span class="hljs-number">0</span>] === element.firstChild;
element.childNodes[element.childNodes.length - <span class="hljs-number">1</span>] === element.lastChild;
</code></pre>
<p><code>nextSibling</code>/<code>previousSibling</code>: returns the next sibling/previous sibling node,  including all of them.</p>
<p><strong>Element specific properties or Element only navigation</strong>: These properties provide a convenient way to access only element nodes, excluding text nodes and comments.</p>
<p><code>children</code> returns a live HTMLCollection of direct child elements, and the <code>parentElement</code> property returns the parent element node of the specified node.</p>
<p>In the below screenshot, you can see the difference between <code>childNodes</code> and <code>children</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-62.png" alt="Image" width="600" height="400" loading="lazy">
<em>Here, Linebreak (text node) will be considered 1st child node of body element, whereas div.color (Blue) will be considered the 1st child.</em></p>
<p>For instance, let's say we have this code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// childnode</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body.childNodes);

<span class="hljs-comment">// children</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body.children);
</code></pre>
<pre><code><span class="hljs-comment">// childnode</span>
NodeList(<span class="hljs-number">19</span>) [text, div.color, text, div.color, text, comment, text, div.color, text, div.color, text, div.color, text, script, text, comment, text, script, text]


<span class="hljs-comment">// children</span>
HTMLCollection(<span class="hljs-number">7</span>) [div.color, div.color, div.color, div.color, div.color, script, script]
</code></pre><p>and, if we refresh the page, the output gets:</p>
<pre><code>NodeList(<span class="hljs-number">14</span>) [text, div.color, text, div.color, text, comment, text, div.color, text, div.color, text, div.color, text, script]
HTMLCollection(<span class="hljs-number">6</span>) [div.color, div.color, div.color, div.color, div.color, script]
</code></pre><p>Initially, the <code>NodeList</code> contains 19 nodes. These nodes consist of text nodes, <code>div</code> elements with the class "color", a comment node, and <code>script</code> elements. The <code>HTMLCollection</code> contains 7 elements, which are the <code>div</code> elements with the class "color" and <code>script</code> elements.</p>
<p>When the page is refreshed, some elements or nodes are removed or modified dynamically through JavaScript or other means, leading to the observed changes in the DOM structure.</p>
<p><code>firstElementChild</code>/<code>lastElementChild</code> returns the first/last child, excluding non-element nodes.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Both will exclude text nodes and comment nodes.</span>
<span class="hljs-built_in">document</span>.body.firstElementChild; <span class="hljs-comment">// Outputs: &lt;div class="color"&gt;</span>
<span class="hljs-built_in">document</span>.body.lastElementChild; <span class="hljs-comment">// Outputs: &lt;script src="script.js"&gt;</span>
</code></pre>
<p><strong>Key Points:</strong></p>
<ul>
<li>Choose the right property based on whether you need to target all nodes or specifically element nodes.</li>
<li>Remember that properties like <code>firstChild</code> and <code>previousSibling</code> might return element and non-element nodes, while their element-specific counterparts (<code>firstElementChild</code> and <code>previousElementSibling</code>) focus only on elements.</li>
</ul>
<h3 id="heading-methods-for-querying-dom-elements">Methods for Querying DOM Elements:</h3>
<p>JavaScript provides several methods for accessing elements in the DOM:</p>
<ul>
<li><strong><code>getElementById</code>:</strong> This method retrieves an element by its unique ID attribute.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myElement"</span>);
</code></pre>
<ul>
<li><strong><code>getElementsByClassName</code>:</strong> This method returns a collection of elements with the specified class name.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> elements = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"myClass"</span>);
</code></pre>
<ul>
<li><strong><code>getElementsByTagName</code>:</strong> This method returns a list of collection of elements with the specified tag name.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> elements = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"div"</span>);
</code></pre>
<ul>
<li><strong><code>querySelector</code>:</strong> This method retrieves the first element that matches a specified CSS selector.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"cssSelector"</span>);
</code></pre>
<ul>
<li><strong><code>querySelectorAll</code>:</strong>  This method retrieves all elements that match a CSS                 selector.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> elements = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"cssSelector"</span>);
</code></pre>
<p>You might be wondering how <code>querySelector</code> differs from <code>querySelectorAll</code>.</p>
<p>Well, <code>querySelector</code> returns the first element within the document that matches the specified selector. On the other hand, <code>querySelectorAll</code> returns a static NodeList representing a list of the document's elements that match the specified group of selectors.</p>
<p>When you're using <code>querySelectorAll</code>, you receive a NodeList, which is similar to an array but not exactly the same. You cannot directly manupulate all elements like appling styles to all elements within a NodeList using methods like <code>style.backgroundColor = 'red'</code>. So we use a <code>forEach</code> loop. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">".box"</span>));

<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.box'</span>).forEach(<span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> {
    <span class="hljs-comment">// Within the forEach loop, we access each element and set its background color to green.</span>
    element.style.backgroundColor = <span class="hljs-string">"green"</span>;
});
</code></pre>
<p>Let's see what's going on in this code:</p>
<ul>
<li>In the first line, we directly change the background color of the element with the class 'box' using querySelector.</li>
<li>In the second line, we use querySelectorAll to select all elements with the class 'box' and log the NodeList to the console.</li>
<li>In third line, since <code>querySelectorAll</code> returns a NodeList, we need to iterate through each element in the NodeList in order to apply the background color to each element separately.</li>
<li>so  basically, we can say <code>querySelector</code> is equivalent to <code>querySelectorAll('section')[0]</code>.</li>
</ul>
<p>Alright, one last method to consider:</p>
<ul>
<li><strong><code>getElementsByName</code></strong>: This method returns a list of collection of elements with the specified name attribute.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> items = <span class="hljs-built_in">document</span>.getElementsByName(<span class="hljs-string">'some-name-attribute'</span>);
<span class="hljs-built_in">console</span>.log(items);
</code></pre>
<p>These methods are important to understand because they are used in various situations. </p>
<p>For example, when we want to select all the <code>div</code> elements in the document, we can use the <code>querySelectorAll</code> method or the <code>getElementsByTagName</code> method. Both methods will return the same result, but <code>querySelectorAll</code> is more flexible because it can select elements that match any CSS selector. <code>getElementsByTagName</code> can only select elements that have the same tag name.</p>
<h3 id="heading-matches-closest-and-contains">Matches, Closest, and Contains:</h3>
<p>When you're working with JavaScript and dealing with web pages, you often need to find specific parts of the page or do things with them. Three methods you might use are <code>matches()</code>, <code>closest()</code>, and <code>contains()</code>.</p>
<p><strong><code>matches()</code></strong> checks if an element matches a certain style rule. For example, if you have a button and you want to see if it has a class of "active", you could use <code>button.matches('.active')</code>. It will return true if the button has that class, and false if it doesn't.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>);
<span class="hljs-keyword">if</span> (button.matches(<span class="hljs-string">'.active'</span>)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The button is active'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The button is not active'</span>);
}
</code></pre>
<p>If you have an element and you want to find its nearest parent with a certain class, you can use <code>**closest()**</code> like this: <code>element.closest('.classname')</code>. </p>
<p>For instance, if you have a  link inside a list item and you want to find the nearest list item, you could do <code>link.closest('li')</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> link = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'a'</span>);
<span class="hljs-keyword">const</span> listItem = link.closest(<span class="hljs-string">'li'</span>);
<span class="hljs-built_in">console</span>.log(listItem); <span class="hljs-comment">// This will give you the nearest list item</span>
</code></pre>
<p>And <strong><code>contains()</code></strong> checks if one element is inside another. For example, if you have a div and a paragraph inside it, you could check if the div contains the paragraph with <code>div.contains(paragraph)</code>. It will return true if the paragraph is inside the div, and false if it's not.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> div = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'div'</span>);
<span class="hljs-keyword">const</span> paragraph = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>);
<span class="hljs-keyword">if</span> (div.contains(paragraph)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The div contains a paragraph'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The div does not contain any paragraph'</span>);
}
</code></pre>
<p>These methods are handy for navigating around your web page and doing different things with its elements.</p>
<h3 id="heading-how-to-inspect-dom-elements">How to Inspect DOM Elements</h3>
<p><strong>Using console.dir():</strong> <code>console.dir()</code> is not a method of the DOM. It's a method provided by the browser's Console API, specifically used for logging JavaScript objects to the console.</p>
<p>If we log an element using <code>console.log()</code>, we see its HTML representation. But with <code>console.dir()</code>, we get an interactive list showing all available attributes and functions for that element.</p>
<p><strong><code>tagName</code></strong> and <code>nodeName</code>: <code>tagName</code> is a property specific to HTML elements. It returns the tag name of an HTML element in uppercase letters. For example, if you have an HTML element <code>&lt;div&gt;</code>, <code>tagName</code> will return <code>"DIV"</code>.</p>
<p>On the other hand, <code>nodeName</code> is a property of DOM nodes that represents the name of the node. For element nodes, it returns the tag name in uppercase. For other types of nodes, it returns a string representing the type of node (for example, "#text" for text nodes, "#comment" for comment nodes).</p>
<p><strong>Discovering a node's type:</strong> Each node in the DOM has a <code>nodeType</code> property that indicates its type. It has a numeric value: <code>1</code> for elements, <code>2</code> for attributes, <code>3</code> for text nodes, <code>8</code> for comment and <code>9</code> for document. Read-only. This property can be used to distinguish between element nodes and text nodes. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> element = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
<span class="hljs-built_in">console</span>.log(element.nodeType); <span class="hljs-comment">// Output: 1</span>
</code></pre>
<h3 id="heading-table-navigation-in-the-dom">Table Navigation in the DOM</h3>
<p>Now, let's learn how to navigate a table element and its child nodes using the DOM. Here, instead of manually writing a table, we will use Bootstrap's pre-designed table.</p>
<p>Before diving into table navigation, let's discuss Bootstrap, a popular front-end framework offering pre-designed components and styles for building responsive web pages efficiently.</p>
<p>To integrate Bootstrap into our project, we'll:</p>
<ol>
<li>Copy the pre-designed table from <a target="_blank" href="https://getbootstrap.com/docs/5.3/content/tables/">here</a>.</li>
<li>Paste it into a container <code>&lt;div&gt;</code> in our HTML.</li>
<li>Include Bootstrap's CSS and JS files in our webpage (which you can copy from <a target="_blank" href="https://getbootstrap.com/docs/5.3/getting-started/introduction/">here</a>).</li>
</ol>
<p>Here's how our HTML code will look after integration:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Table Navigation<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"styles.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Bootstrap Table --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">table</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"table"</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- Table Header --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">thead</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>#<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>First<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>Last<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>Handle<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">thead</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- Table Body --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Mark<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Otto<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>@mdo<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Jacob<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Thornton<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>@fat<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span> <span class="hljs-attr">colspan</span>=<span class="hljs-string">"2"</span>&gt;</span>Larry the Bird<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>@twitter<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h4 id="heading-table-navigation-properties">Table navigation properties:</h4>
<p>The table element supports various properties for convenient navigation, such as:</p>
<ul>
<li><code>table.rows</code>: Returns an HTMLCollection of all rows in the table.</li>
<li><code>table.caption</code>: Returns the caption element of the table.</li>
<li><code>table.tHead</code>: Returns the thead element of the table.</li>
<li><code>table.tFoot</code>: Returns the tfoot element of the table.</li>
<li><code>table.tBodies</code>: Returns an HTMLCollection of all tbody elements in the table.</li>
</ul>
<p>Similarly, the tr (table row) element supports properties like:</p>
<ul>
<li><code>tr.cells</code>: Returns an HTMLCollection of all cells in the row.</li>
<li><code>tr.sectionRowIndex</code>: Returns the index of the row in the current section (thead, tbody, or tfoot).</li>
<li><code>tr.rowIndex</code>: Returns the index of the row in the table.</li>
</ul>
<p>The td (table cell) element also supports the <code>td.cellIndex</code> property, returning the index of the cell in the row.</p>
<p>For instance, to print all rows in the table:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> t = <span class="hljs-built_in">document</span>.body.firstElementChild.firstElementChild; <span class="hljs-comment">// Selecting the table</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; t.rows.length; i++) {
    <span class="hljs-keyword">let</span> row = t.rows[i];
    <span class="hljs-built_in">console</span>.log(row)
}
</code></pre>
<p>To print cells in the first row:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> t = <span class="hljs-built_in">document</span>.body.firstElementChild.firstElementChild; <span class="hljs-comment">// Selecting the table</span>
<span class="hljs-keyword">let</span> row = t.rows[<span class="hljs-number">0</span>]; <span class="hljs-comment">// Selecting the first row</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; row.cells.length; i++) {
    <span class="hljs-keyword">let</span> cell = row.cells[i];
    <span class="hljs-built_in">console</span>.log(cell)
}
</code></pre>
<h2 id="heading-how-to-modify-dom-elements">How to Modify DOM Elements</h2>
<p>Once you have access to DOM elements, you can modify them in various ways using JavaScript.</p>
<h3 id="heading-how-to-manipulate-element-content-and-visibility">How to Manipulate Element Content and Visibility</h3>
<h4 id="heading-innerhtml-and-outerhtml"><code>innerHTML</code> and <code>outerHTML</code></h4>
<p>You can use <code>innerHTML</code> to access or change the HTML content inside an element as a string. <code>outerHTML</code>, on the other hand, lets you get or set the HTML content of an element as a string, including the original element itself.</p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    Hello World
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Hey I am span<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> first = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"span"</span>)[<span class="hljs-number">0</span>]; <span class="hljs-comment">// </span>

<span class="hljs-comment">// log and change inner HTML</span>
<span class="hljs-built_in">console</span>.log(first.innerHTML); <span class="hljs-comment">// Output: Hey I am span</span>
first.innerHTML = <span class="hljs-string">"Hey I am changed"</span>; <span class="hljs-comment">// Modify the content of the &lt;span&gt; element</span>

<span class="hljs-comment">// log and change outer HTML</span>
<span class="hljs-built_in">console</span>.log(first.outerHTML); <span class="hljs-comment">// Output: &lt;span&gt;Hey I am span&lt;/span&gt;</span>
first.outerHTML = <span class="hljs-string">"&lt;h1&gt;Hey I am changed&lt;/h1&gt;"</span>; <span class="hljs-comment">// Reload the page to see the change</span>
</code></pre>
<h4 id="heading-textcontent-property"><code>textContent</code> property</h4>
<p>The <code>textContent</code> property allows you to set or retrieve the text content of an element, ignoring any HTML tags within it. It's useful when you want to update the text content of an element without affecting its HTML structure.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(first.textContent); <span class="hljs-comment">// output: Hey I am span</span>

<span class="hljs-comment">// change the text content</span>
first.textContent = <span class="hljs-string">"Hey I am changed"</span>;
</code></pre>
<h4 id="heading-innertext-property"><code>innerText</code> property</h4>
<p>The <code>innerText</code> property returns only the visible text content of an element, excluding any text within <code>&lt;script&gt;</code> and <code>&lt;style&gt;</code> elements, and accounting for CSS styling that affects visibility. It takes into account CSS styling, such as <code>display: none</code>, <code>visibility: hidden</code>, and so on and returns only the text that is rendered on the screen. </p>
<h4 id="heading-style-property"><code>style</code> property</h4>
<p>This property provides access to an object for manipulating an element's inline styles (for example, <code>element.style.color = "red"</code>).</p>
<h4 id="heading-hidden-property"><code>hidden</code> property</h4>
<p>The <code>hidden</code> provides a simple and convenient way to control the visibility of elements in the DOM without directly manipulating their style properties.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'span'</span>)[<span class="hljs-number">0</span>].hidden = <span class="hljs-literal">true</span>;

<span class="hljs-comment">// When hidden is set to false, the element is visible.</span>
</code></pre>
<p>Note that setting an element's <code>hidden</code> property to <code>true</code> only hides it from view, but it still occupies space in the document layout. </p>
<h3 id="heading-how-to-modify-element-attributes">How to Modify Element Attributes</h3>
<p>The <code>getAttribute()</code> method retrieves the value of a specified attribute of an element, while <code>setAttribute()</code> sets or updates the value of a specified attribute. </p>
<p><code>hasAttribute()</code> checks whether an element has a specific attribute, returning true or false. The <code>removeAttribute()</code> method removes a specified attribute from an element.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-68.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In HTML5, it's possible to define custom attributes for elements. But to prevent potential conflicts with future HTML or JavaScript updates, you should prefix custom attributes with <code>data-</code>. For instance:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"element1"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"sample"</span> <span class="hljs-attr">data-category</span>=<span class="hljs-string">"music"</span> <span class="hljs-attr">data-rating</span>=<span class="hljs-string">"5"</span>&gt;</span>
    This is the first element.
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>To access these custom attributes using JavaScript, we can utilize the <code>dataset</code> property. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(element1.dataset);
</code></pre>
<p>This will display a <code>DOMStringMap</code> object containing all the custom attributes associated with the "element1" div. Specific custom attributes can also be accessed by their names. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(element1.dataset.category);

<span class="hljs-comment">// This code would output the value of the "category" custom attribute, which in this case is "music"</span>
</code></pre>
<h3 id="heading-html-insertion-methods">HTML Insertion Methods</h3>
<p>In HTML, there are several ways to insert new content or modify existing content dynamically using JavaScript. These are known as HTML insertion methods. </p>
<p>Consider the following HTML as our example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>first element<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h4 id="heading-classic-way-to-insert-html">Classic Way to Insert HTML:</h4>
<p>A conventional way to insert HTML is by using the <code>innerHTML</code> property. For example, let's say we want to add an <code>h1</code> element with the text "Hello World" inside the first <code>div</code>. We can do this using the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'div'</span>)[<span class="hljs-number">0</span>];
a.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World&lt;/h1&gt;'</span>;
</code></pre>
<p>We could also append new HTML to the existing HTML inside the <code>div</code> element. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// This will retain the old content and add a new h1 element.</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'div'</span>)[<span class="hljs-number">0</span>];
a.innerHTML = a.innerHTML + <span class="hljs-string">'&lt;h1&gt;Hello World&lt;/h1&gt;'</span>;
</code></pre>
<h4 id="heading-using-createelement-to-insert-html">Using <code>createElement</code> to Insert HTML:</h4>
<p>Another method involves creating a new element using <code>createElement</code>, setting its content using <code>innerHTML</code>, and subsequently appending it to the target element using <code>appendChild</code>.</p>
<h4 id="heading-other-html-insertion-methods">Other HTML Insertion Methods:</h4>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
I am outside div (start)
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
    I am start of this container
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>I am first element<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    I am end of this container
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
I am outside div (end)
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Now, let's consider other methods for inserting HTML content dynamically:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'div'</span>)[<span class="hljs-number">0</span>];

<span class="hljs-comment">// Using createElement and appendChild</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (append)&lt;/h1&gt;'</span>;
a.appendChild(div);

<span class="hljs-comment">// Using prepend</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (prepend)&lt;/h1&gt;'</span>;
a.prepend(div);

<span class="hljs-comment">// Using before</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (before)&lt;/h1&gt;'</span>;
a.before(div);

<span class="hljs-comment">// Using after</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (after)&lt;/h1&gt;'</span>;
a.after(div);

<span class="hljs-comment">// Using replaceWith</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (replaced)&lt;/h1&gt;'</span>;
a.replaceWith(div);
</code></pre>
<p>This code demonstrates different methods for dynamically inserting HTML content into the DOM using JavaScript.</p>
<ul>
<li><code>a.append(div)</code>: This method appends the <code>div</code> element as the last child of the <code>a</code> element.</li>
<li><code>a.prepend(div)</code>: This method adds the <code>div</code> element as the first child of the <code>a</code> element.</li>
<li><code>a.before(div)</code>: This method adds the <code>div</code> element before the <code>a</code> element.</li>
<li><code>a.after(div)</code>: This method adds the <code>div</code> element after the <code>a</code> element.</li>
<li><code>a.replaceWith(div)</code>: This method replaces the <code>a</code> element with the <code>div</code> element.</li>
</ul>
<h3 id="heading-the-insertadjacenthtml-insertadjacentelement-and-insertadjacenttext-methods">The <code>insertAdjacentHTML</code>, <code>insertAdjacentElement</code>, and <code>insertAdjacentText</code> Methods</h3>
<p>These methods are used to insert content into the DOM at a specified position relative to a given element. They are helpful when you need to dynamically add new elements or text to your webpage.</p>
<h4 id="heading-insertadjacenthtml"><code>insertAdjacentHTML</code>:</h4>
<p><code>insertAdjacentHTML</code> allows you to insert a string of HTML at a specified position relative to the element.</p>
<p>The first parameter specifies where the HTML string will be inserted:</p>
<ul>
<li><code>beforebegin</code>: Before the element itself.</li>
<li><code>afterbegin</code>: Just inside the element, before its first child.</li>
<li><code>beforeend</code>: Just inside the element, after its last child.</li>
<li><code>afterend</code>: After the element itself.</li>
</ul>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
element.insertAdjacentHTML(<span class="hljs-string">'beforebegin'</span>, <span class="hljs-string">'&lt;div&gt;New content&lt;/div&gt;'</span>);
</code></pre>
<h4 id="heading-insertadjacentelement"><code>insertAdjacentElement</code>:</h4>
<p>It's similar to <code>insertAdjacentHTML</code>, but instead of inserting HTML, you can insert a DOM element.</p>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
<span class="hljs-keyword">let</span> newElement = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
newElement.textContent = <span class="hljs-string">'New content'</span>;
element.insertAdjacentElement(<span class="hljs-string">'beforebegin'</span>, newElement);
</code></pre>
<h4 id="heading-insertadjacenttext"><code>insertAdjacentText</code>:</h4>
<p>It's similar to <code>insertAdjacentHTML</code>, but instead of inserting HTML, you can insert plain text.</p>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
element.insertAdjacentText(<span class="hljs-string">'beforebegin'</span>, <span class="hljs-string">'New content'</span>);
</code></pre>
<h4 id="heading-node-removal">Node Removal:</h4>
<p>The <code>remove</code> method removes the element from the DOM.</p>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
element.remove();
</code></pre>
<p>These methods allow you to manipulate the DOM dynamically, adding or removing content based on certain conditions or user interactions.</p>
<p>When using <code>insertAdjacentHTML</code>, <code>insertAdjacentElement</code>, or <code>insertAdjacentText</code>, you specify where the new content should be inserted relative to the given element.</p>
<p>When using <code>remove</code>, you simply remove the element from the DOM entirely.</p>
<p>These methods are helpful for dynamically updating the content of your webpage without having to reload the entire page.</p>
<h3 id="heading-how-to-manipulate-classes-with-javascript">How to Manipulate Classes with JavaScript</h3>
<p>In HTML, we use classes to group elements and apply styles using CSS. For example, we have a div with an id of "first" in our HTML.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Hello, this is text<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>We also have CSS styles for classes like "yellow", "red", and "text-dark" to change background color and text color.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.yellow</span> {
    <span class="hljs-attribute">background-color</span>: yellow;
    <span class="hljs-attribute">color</span>: white;
}
<span class="hljs-selector-class">.red</span> {
    <span class="hljs-attribute">background-color</span>: red;
    <span class="hljs-attribute">color</span>: white;
}
<span class="hljs-selector-class">.text-dark</span> {
    <span class="hljs-attribute">color</span>: black;
}
</code></pre>
<p><strong><code>className</code>:</strong> In JavaScript, we can change the class of an element using the <code>className</code> property. For instance, if we want to change the class of the element with the id "first" to "red text-dark", we would do:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// we are applying 2 classes here</span>
first.className = <span class="hljs-string">"red text-dark"</span>;
</code></pre>
<p>If we want to add another class without removing the existing ones, we use the <code>+=</code> operator:</p>
<pre><code class="lang-javascript">first.className += <span class="hljs-string">" yellow"</span>; <span class="hljs-comment">// Adds the class "yellow" without removing existing classes</span>
</code></pre>
<p><strong><code>classList</code>:</strong> The <code>classList</code> property allows you to manipulate the classes of an element. We can use methods like <code>add</code>, <code>remove</code>, <code>toggle</code>, and <code>contains</code> to add, remove, toggle, or check the presence of a class.</p>
<ul>
<li><code>classList.remove()</code>: Removes a specific class from the element:</li>
</ul>
<pre><code class="lang-javascript">first.classList.remove(<span class="hljs-string">'text-dark'</span>); <span class="hljs-comment">// Removes the class "text-dark"</span>
</code></pre>
<ul>
<li><code>classList.add()</code>: But wait, it looked better with that class! We can also add it back with:</li>
</ul>
<pre><code class="lang-javascript">first.classList.add(<span class="hljs-string">'text-dark'</span>); <span class="hljs-comment">// Adds the class "text-dark"</span>
</code></pre>
<ul>
<li><code>classList.toggle()</code>: Toggles a class on or off based on its presence:</li>
</ul>
<pre><code class="lang-javascript">first.classList.toggle(<span class="hljs-string">'text-dark'</span>); <span class="hljs-comment">// Toggles the class "text-dark" (adds if absent, removes if present)</span>
</code></pre>
<ul>
<li><code>classList.contains()</code>: Checks if a class is present on the element:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(first.classList.contains(<span class="hljs-string">'text-dark'</span>)); <span class="hljs-comment">// Returns true if the class "text-dark" is present</span>
</code></pre>
<h2 id="heading-event-handling-in-the-dom">Event Handling in the DOM</h2>
<p>Events are actions or occurrences that happen in the system you are programming, that the system may need to respond to in some way. </p>
<p>In the context of web development, events (<strong>Browser Events</strong>) can be user interactions like clicks, mouse movements, key presses, and so on. JavaScript allows you to handle these events and perform actions in response to them.</p>
<p>In HTML, you can directly specify what should happen when an event occurs using attributes like <code>onclick</code>, <code>onmouseover</code>, and so on. For example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('hello')"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>While you can write JavaScript directly in HTML attributes, it's always better to keep your HTML clean and handle events in JavaScript code separately. This makes your code easier to read and maintain.</p>
<p>You can do this by selecting elements from the webpage using JavaScript and then attaching an event handler to them. Here's how you might do it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> container = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"container"</span>);
container.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hey, this is logged from the script!"</span>);
}
</code></pre>
<p>In this code, we select the element with the id "container" using <code>document.getElementById()</code>. Then, we attach a function to the <code>onclick</code> event of that element. This function will be executed whenever the element is clicked.</p>
<h3 id="heading-common-types-of-events">Common Types of Events:</h3>
<ol>
<li><p><strong>Mouse Events</strong>: These events are related to interactions with the mouse. </p>
</li>
<li><p><strong>click</strong>: When you click on an element.</p>
</li>
<li><strong>contextmenu</strong>: When you right-click on an element.</li>
<li><strong>mouseover / mouseout</strong>: When the mouse cursor enters or leaves an element.</li>
<li><strong>mousedown / mouseup</strong>: When you press or release a mouse button over an element.</li>
<li><strong>mousemove</strong>: When the mouse is moved.</li>
</ol>
<p>Some Examples of Mouse Events:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Mouse Button Property Example:</span>

&lt;div onmousedown=<span class="hljs-string">"console.log('Mouse button:', event.button)"</span>&gt;Click me&lt;/div&gt;
</code></pre>
<p>In this example, the event.button property is used to log which mouse button was pressed.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Modifier Keys Example:</span>

&lt;div onclick=<span class="hljs-string">"if(event.ctrlKey) console.log('Ctrl + Click!')"</span>&gt;Ctrl + Click Me&lt;/div&gt;
</code></pre>
<p>This example logs a message when the user clicks the element while holding the Ctrl key.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Coordinates Example:</span>

&lt;div onmousemove=<span class="hljs-string">"console.log('clientX:', event.clientX, 'clientY:', event.clientY)"</span>&gt;Move your mouse here&lt;/div&gt;
</code></pre>
<p>This example logs the clientX and clientY coordinates of the mouse pointer as it moves over the element.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Preventing Selection Example:</span>

&lt;span ondblclick=<span class="hljs-string">"console.log('Double clicked!')"</span> onmousedown=<span class="hljs-string">"return false;"</span>&gt;Double-click me&lt;/span&gt;
</code></pre>
<p>In this example, the return false statement in the onmousedown event handler prevents the default selection behavior when the element is double-clicked.</p>
<ol start="2">
<li><strong>Keyboard Events –</strong> <strong>keydown / keyup</strong>: When a key is pressed or released on the keyboard.</li>
</ol>
<p>Some Examples of Keyboard Events:</p>
<pre><code class="lang-javascript">&lt;input type=<span class="hljs-string">"text"</span> onkeydown=<span class="hljs-string">"console.log('Key pressed!')"</span> onkeyup=<span class="hljs-string">"console.log('Key released!')"</span>&gt;
</code></pre>
<p>In this example, the input field triggers events when a key is pressed (keydown) and released (keyup).</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Event Modifiers Example:</span>

&lt;input type=<span class="hljs-string">"text"</span> onkeydown=<span class="hljs-string">"if(event.ctrlKey &amp;&amp; event.key === 'c') console.log('Ctrl + C pressed!')"</span>&gt;
</code></pre>
<p>This example logs a message when the user presses the Ctrl key and 'c' key simultaneously in the input field.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Accessing Key Information Example:</span>

&lt;input type=<span class="hljs-string">"text"</span> onkeydown=<span class="hljs-string">"console.log('Key pressed:', event.key)"</span>&gt;
</code></pre>
<p>This example logs the key that was pressed in the input field.</p>
<ol start="3">
<li><p><strong>Form Element Events</strong>: These events occur when you interact with form elements, like submitting a form, focusing on an input field, and so on.</p>
</li>
<li><p><strong>Document Events</strong>: These events are related to the document object itself. Example: <strong>DOMContentLoaded</strong> (when the HTML is fully loaded and the DOM is ready)</p>
</li>
<li><p><strong>CSS Events</strong>: These events are related to CSS animations. Example: <strong>transitionend</strong> (When a CSS animation finishes)</p>
</li>
</ol>
<p>Now, let's see an example demonstrating the practical application of event handling and input validation in web development:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Input Validation Example<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkPhoneNumber</span>(<span class="hljs-params">event</span>) </span>{
  <span class="hljs-keyword">const</span> validKeys = [<span class="hljs-string">'0'</span>, <span class="hljs-string">'1'</span>, <span class="hljs-string">'2'</span>, <span class="hljs-string">'3'</span>, <span class="hljs-string">'4'</span>, <span class="hljs-string">'5'</span>, <span class="hljs-string">'6'</span>, <span class="hljs-string">'7'</span>, <span class="hljs-string">'8'</span>, <span class="hljs-string">'9'</span>, <span class="hljs-string">'+'</span>, <span class="hljs-string">'('</span>, <span class="hljs-string">')'</span>, <span class="hljs-string">'-'</span>];
  <span class="hljs-keyword">if</span> (!validKeys.includes(event.key)) {
    event.preventDefault(); <span class="hljs-comment">// Prevent default action for invalid keys</span>
  }
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"phone"</span>&gt;</span>Enter Phone Number:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"tel"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"phone"</span> <span class="hljs-attr">onkeydown</span>=<span class="hljs-string">"checkPhoneNumber(event)"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Only digits, +, (, ), and - are allowed.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this example, we're implementing input validation for a phone number input field. The <code>onkeydown</code> event triggers the <code>checkPhoneNumber</code> function, which checks if the pressed key is valid (digits, plus sign, parentheses, or hyphen). If the key is not valid, the default action (character input) is prevented.</p>
<p>You can <a target="_blank" href="https://www.freecodecamp.org/news/dom-events-and-javascript-event-listeners/">explore more about events here</a>.</p>
<h3 id="heading-event-handlers">Event Handlers</h3>
<p>To react to these events, we use event handlers. An event handler is simply a function that runs when a specific event occurs. There are different ways to assign event handlers in JavaScript:</p>
<ol>
<li><strong>HTML Attribute</strong>: You can set an event handler directly in the HTML code using an attribute like <code>onclick</code>, <code>onmouseover</code>, etc.</li>
</ol>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('Button clicked!')"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<ol start="2">
<li><strong>DOM Property</strong>: You can assign a handler using a DOM property like <code>onclick</code>, <code>onmouseover</code>, and so on.</li>
</ol>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">'Button clicked!'</span>);
  };
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<ol start="3">
<li><strong>Event Listeners</strong>: Event listeners are functions that wait for a specific event to occur and then execute a designated function. This is typically done using the <code>addEventListener</code> method. </li>
</ol>
<h3 id="heading-addeventlistener-and-removeeventlistener"><code>addEventListener()</code> and <code>removeEventListener()</code>:</h3>
<p>These are methods used to assign and remove event handlers, respectively, in JavaScript.</p>
<ul>
<li><code>**addEventListener()**</code> is used to attach an event listener to an element, which listens for a specific event (for example, a click or mouseover). It provides more flexibility, especially when you need to add multiple handlers to the same event.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">'Button clicked!'</span>);
  });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'btn'</span>);

<span class="hljs-comment">// Example 1: Adding event listeners directly with anonymous functions</span>
btn.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked!"</span>); <span class="hljs-comment">// Logs a message when the button is clicked</span>
});

<span class="hljs-comment">// Example 2: Defining functions separately and then adding event listeners</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello!"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">farewell</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Goodbye!"</span>);
}
btn.addEventListener(<span class="hljs-string">'mouseenter'</span>, greet); <span class="hljs-comment">// Greets when the mouse enters the button</span>
btn.addEventListener(<span class="hljs-string">'mouseleave'</span>, farewell); <span class="hljs-comment">// Says goodbye when the mouse leaves the button</span>
</code></pre>
<p>With <code>addEventListener</code>, you can also specify additional options as a third argument. Some common options are:</p>
<ul>
<li><code>once</code>: A boolean value that specifies whether the event listener should be removed after it is invoked once.</li>
<li><code>capture</code>: A boolean value that specifies whether the event should be captured during the capturing phase. The capturing phase happens before the bubbling phase.</li>
</ul>
<p>For example:</p>
<pre><code class="lang-javascript">btn.addEventListener(<span class="hljs-string">'click'</span>, handleClick, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> });
</code></pre>
<p>This will add a click event listener to the button element that is triggered only once and captures the event during the capturing phase.</p>
<ul>
<li><code>**removeEventListener()**</code> is used to remove a previously attached event listener from an element. </li>
</ul>
<pre><code class="lang-html">// Example 1

<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">'Button clicked!'</span>);
  }

  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">'click'</span>, handleClick);
  <span class="hljs-comment">// Remove the event handler</span>
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).removeEventListener(<span class="hljs-string">'click'</span>, handleClick);
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 2</span>
<span class="hljs-comment">// Assume a user preference</span>
<span class="hljs-keyword">const</span> allowGreetings = <span class="hljs-literal">true</span>;

<span class="hljs-comment">// Removing event listeners based on user preference</span>
<span class="hljs-keyword">if</span> (!allowGreetings) {
    btn.removeEventListener(<span class="hljs-string">'mouseenter'</span>, greet);
}
</code></pre>
<h3 id="heading-object-handlers-handleevent">Object Handlers: <code>handleEvent</code></h3>
<p>Instead of assigning a function as an event handler, you can also assign an object that has a <code>handleEvent</code> method. When the event occurs, the <code>handleEvent</code> method of the object will be called.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> myObject = {
    <span class="hljs-attr">handleEvent</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
      alert(<span class="hljs-string">'Button clicked!'</span>);
    }
  };

  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">'click'</span>, myObject);
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>In this example, when the button is clicked, the <code>handleEvent</code> method of <code>myObject</code> is called.</p>
<h3 id="heading-event-object">Event Object:</h3>
<p>When an event occurs, the browser creates an event object that contains information about the event, such as the type of event, the target element, and any additional data. </p>
<p>This object is passed as an argument to the event handler function which can be accessed within the callback function of an event listener.</p>
<pre><code class="lang-javascript">element.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-built_in">console</span>.log(event.type); <span class="hljs-comment">// Output: "click"</span>
    <span class="hljs-built_in">console</span>.log(event.target); <span class="hljs-comment">// Output: The element that was clicked</span>
     <span class="hljs-comment">// We can access more properties like event.clientX, event.clientY, etc.</span>
});
</code></pre>
<h3 id="heading-event-propagation">Event Propagation:</h3>
<p>Events in the DOM can propagate through the DOM tree in two phases: the capturing phase and bubbling phase. </p>
<p>When an event happens on an element, like a click or a key press, the browser needs to decide which elements should be notified about the event. </p>
<p>Event capturing and bubbling describe the order in which elements are notified about the event. Understanding event propagation is important when dealing with nested elements and event delegation.</p>
<ol>
<li><strong>Capturing Phase</strong>: In the capturing phase, the event starts from the top of the DOM hierarchy (usually the <code>&lt;html&gt;</code> element) and travels down to the target element. During this phase, event handlers attached with <code>addEventListener</code> and the <code>capture</code> option set to <code>true</code> are triggered. These handlers are executed before the event reaches the target element.</li>
<li><strong>Target Phase</strong>: Once the event reaches the target element, it enters the target phase. Event handlers attached with <code>addEventListener</code> without the <code>capture</code> option (or with <code>false</code> as the value) are triggered during this phase. Handlers attached in this phase are executed when the event is directly targeting the element.</li>
<li><strong>Bubbling Phase</strong>: After the target phase, the event bubbles up from the target element to the top of the DOM hierarchy. During this phase, event handlers attached with <code>addEventListener</code> without the <code>capture</code> option (or with <code>false</code> as the value) are triggered again. Handlers attached in this phase are executed as the event travels up from the target element.</li>
</ol>
<p>Let's look at an example. Consider a <code>&lt;div&gt;</code> nested inside another <code>&lt;div&gt;</code>. If a click event occurs on the inner <code>&lt;div&gt;</code>, the capturing phase starts from the outer <code>&lt;div&gt;</code> and goes down to the inner <code>&lt;div&gt;</code>. Then, the target phase happens on the inner <code>&lt;div&gt;</code>, and finally, the bubbling phase occurs from the inner <code>&lt;div&gt;</code> back up to the outer <code>&lt;div&gt;</code>.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"outerDiv"</span>&gt;</span>
  Outer Div
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"innerDiv"</span>&gt;</span>Inner Div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">const</span> outerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'outerDiv'</span>);
  <span class="hljs-keyword">const</span> innerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'innerDiv'</span>);

  outerDiv.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Capturing: Outer Div'</span>), <span class="hljs-literal">true</span>);
  innerDiv.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Target: Inner Div'</span>));
  outerDiv.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Bubbling: Outer Div'</span>));
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Let's understand Bubbling in detail.</p>
<h3 id="heading-event-bubbling">Event Bubbling:</h3>
<p>Event bubbling is a mechanism in JavaScript where, when an event occurs on an element, such as a click, that event first triggers on the target element and then "bubbles" up through its ancestor elements all the way up to the root of the document (usually <code>&lt;html&gt;</code>). This triggers the same event on each ancestor along the way. Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('form')"</span>&gt;</span>
  FORM
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('div')"</span>&gt;</span>
    DIV
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('p')"</span>&gt;</span>P<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>If you click on the <code>&lt;p&gt;</code> element, the click event will first trigger on the <code>&lt;p&gt;</code> element, then on the <code>&lt;div&gt;</code>, and finally on the <code>&lt;form&gt;</code>. This is because the event bubbles up through each parent element in the DOM hierarchy.</p>
<p><strong><code>event.target</code></strong> vs. <code>this</code>:</p>
<ul>
<li><code>event.target</code> refers to the element that initiated the event. It remains the same throughout the bubbling process. In the above example, if you click on the <code>&lt;p&gt;</code> element, <code>event.target</code> will be the <code>&lt;p&gt;</code> element.</li>
<li><code>this</code> (or <code>event.currentTarget</code>) refers to the current element that the event handler is attached to. In the above example, if the event handler is attached to the <code>&lt;form&gt;</code>, <code>this</code> will be the <code>&lt;form&gt;</code> element.</li>
</ul>
<h4 id="heading-how-to-stop-event-bubbling">How to stop event bubbling:</h4>
<p>Sometimes, you might want to stop the event from bubbling up further. You can do this using the <code>event.stopPropagation()</code> method. This method stops the event from propagating to parent elements.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('the bubbling doesn't reach here')"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"event.stopPropagation()"</span>&gt;</span>Click here<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>In this example, clicking the button won't trigger the <code>alert</code> on the body element because <code>event.stopPropagation()</code> is called in the button's click event handler.</p>
<p><code>event.stopImmediatePropagation()</code> is similar to <code>event.stopPropagation()</code>, but also prevents other handlers on the current element from executing.</p>
<h3 id="heading-event-delegation">Event Delegation:</h3>
<p>Event delegation is a technique that allows you to handle events more efficiently by attaching a single event listener to a parent element instead of attaching multiple event listeners to individual child elements. This is particularly useful when you have a large number of similar elements that need the same event handling logic.</p>
<pre><code class="lang-javascript">parentElement.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-keyword">if</span> (event.target.classList.contains(<span class="hljs-string">'childElement'</span>)) {
        <span class="hljs-comment">// Action to be performed when a child element is clicked</span>
    }
});
</code></pre>
<pre><code class="lang-javascript">&lt;!-- Example: Event delegation --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myList"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Item 1<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Item 2<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Item 3<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-comment">// Adding a click event listener to the parent ul element</span>
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myList"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
        <span class="hljs-comment">// Checking if the clicked element is an li</span>
        <span class="hljs-keyword">if</span> (event.target.tagName === <span class="hljs-string">"LI"</span>) {
            <span class="hljs-comment">// Code to execute when an li is clicked</span>
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Item clicked:"</span>, event.target.textContent);
        }
    });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>This approach reduces the number of event listeners and improves performance.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The DOM, or Document Object Model, is an interface that represents the structure of HTML documents. It serves as the bridge between JavaScript code and the browser, allowing manipulation of HTML elements, styles, attributes, and event handling. </p>
<p>The DOM API provides methods and properties to interact with the DOM tree. Examples include <code>querySelector</code>, <code>addEventListener</code>, <code>createElement</code>, <code>innerHTML</code>, <code>textContent</code>, etc.</p>
<p>Through DOM manipulation, developers can dynamically change various aspects of a web page, including text content, HTML attributes, and the structure of the document itself (for example, inserting, updating, or deleting HTML elements).</p>
<p>JavaScript frameworks and libraries like React often utilize DOM manipulation capabilities to efficiently manage and update user interfaces. This lets developers create complex web applications with interactive and responsive user experiences.</p>
<p>To learn more about the DOM, here are a few resources you can check out:</p>
<p>First of all, I wrote a follow-up article, which you can find here:<br><a class="post-section-overview" href="#https://www.freecodecamp.org/news/form-validation-in-javascript/">Client-Side Form Handling with JavaScript</a>.</p>
<p>You can also read more in the following articles:</p>
<ul>
<li><a target="_blank" href="https://www.samyakinfo.tech/blog/document-and-resource-loading">DOM Events Lifecycle and Efficient script Loading</a></li>
<li>The <a target="_blank" href="https://www.freecodecamp.org/news/the-javascript-dom-manipulation-handbook/">JavaScript DOM manipulation handbook</a></li>
<li>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model">MDN</a> web docs</li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/dom-manipulation-best-practices/">JavaScript DOM manipulation best practices</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-javascript-for-dom-manipulation-in-spanish-course-for-beginners/">JS DOM manipulation in Spanish - full course</a></li>
</ul>
<p></p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JS DOM Manipulation Best Practices – with Examples ]]>
                </title>
                <description>
                    <![CDATA[ In JavaScript, you can manipulate the content of a web page using the Document Object Model (DOM). But how do you write code that is readable, easy to maintain, and not prone to performance issues? That's what we'll cover in this article. I'll discus... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dom-manipulation-best-practices/</link>
                <guid isPermaLink="false">66d45dd6aad1510d0766b5e9</guid>
                
                    <category>
                        <![CDATA[ best practices ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Benjamin Semah ]]>
                </dc:creator>
                <pubDate>Fri, 12 Jan 2024 17:41:27 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/01/freecodecamp-javascript-benjamin-semah.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In JavaScript, you can manipulate the content of a web page using the Document Object Model (DOM). But how do you write code that is readable, easy to maintain, and not prone to performance issues?</p>
<p>That's what we'll cover in this article. I'll discuss some important best practices so that you can manipulate the DOM with confidence.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#">Introduction</a></p>
</li>
<li><p><a class="post-section-overview" href="#user-the-domcontentloaded-event">Use the DOMContentLoaded Event</a></p>
</li>
<li><p><a class="post-section-overview" href="#cache-selected-elements">Cache Selected Elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#query-parent-elements-instead-of-document">Query Parent Instead of Document</a></p>
</li>
<li><p><a class="post-section-overview" href="#use-css-classes-to-style-elements">Use CSS Classes to Style Elements</a></p>
</li>
<li><p><a class="post-section-overview" href="#use-innerhtml-with-caution">Use innerHTML With Caution</a></p>
</li>
<li><p><a class="post-section-overview" href="#write-readable-event-listeners">Write Readable Event Listeners</a></p>
</li>
<li><p><a class="post-section-overview" href="#use-event-delegation-to-handle-dom-events">Use Event Delegation to Handle DOM Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#batch-dom-updates-with-fragment">Batch DOM Updates With Fragment</a></p>
</li>
<li><p><a class="post-section-overview" href="#use-the-stoppropagation-method">Use the stopPropagation Method</a></p>
</li>
<li><p><a class="post-section-overview" href="#test-your-dom-manipulation-code">Test your DOM Manipulation code</a></p>
</li>
<li><p><a class="post-section-overview" href="#conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-user-the-domcontentloaded-event">User the <code>DOMContentLoaded</code> Event</h2>
<p>The <code>DOMContentLoaded</code> event is fired when the HTML document is fully loaded. Using this event ensures that your DOM manipulation code runs only after the document is fully loaded.</p>
<p>To use the <code>DOMContentLoaded</code>, add an event listener to the document and listen for the <code>DOMContentLoaded</code> event. This helps prevent any issues that may come up when you try to manipulate elements that are yet to be rendered.</p>
<p>Example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'DOMContentLoaded'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Your DOM manipulation code goes here...</span>
})
</code></pre>
<h2 id="heading-cache-selected-elements">Cache Selected Elements</h2>
<p>When you have frequently used elements, querying the DOM for the same element anytime over and over is inefficient. It's better to query the DOM once and store the result in variables.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cachedElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'exampleId'</span>)
</code></pre>
<p>This way you can reference the variables anytime you want to use them. This helps improve performance as it reduces unnecessary work.</p>
<h2 id="heading-query-parent-elements-instead-of-document">Query Parent Elements Instead of Document</h2>
<p>When you cache an element, you can also query it to select any of its descendants. This can help improve performance because it limits the scope of the query and reduces the number of times the entire document is queried.</p>
<p>Example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"parent"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"child"</span>&gt;</span>Example paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> parentElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'parent'</span>)

<span class="hljs-comment">// Options 1: Querying entire document ❌</span>
<span class="hljs-keyword">const</span> childFromDocument = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'child'</span>) 

<span class="hljs-comment">// Options 2: Query the parent element ✅</span>
<span class="hljs-keyword">const</span> childFromParent = parentElement.querySelector(<span class="hljs-string">'#child'</span>)
</code></pre>
<p>In the example above is a simple markup containing a <code>#parent</code> div and <code>.child</code> paragraph. Then there are two options for selecting the child element.</p>
<p>Technically, both options are correct and will select the same element. But the difference is in the scope of the query.</p>
<p>Example 1 queries (or searches) the entire document to find and select the child. This is less performant and not even necessary because the parent of the element you intend to select is already cached.</p>
<p>Example 2 narrows the scope of the query (or search) by querying only the parent element and not the whole document. That's why it's preferred because it's more performant – especially when the document is large.</p>
<p>Also, note that the method used for querying the parent is <code>querySelector</code>. Using <code>getElementById</code> to query the parent won't work and will result in an error.</p>
<h2 id="heading-use-css-classes-to-style-elements">Use CSS Classes to Style Elements</h2>
<p>It's best to use CSS classes to style elements instead of using inline styles. Classes are easy to maintain compared to inline styles which can be hard to manage.</p>
<p>The <code>classList</code> property has useful properties like add, remove, toggle, and others that makes it easy to modify styles.</p>
<p>Example:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.styledClass</span> {
  <span class="hljs-attribute">color</span>: red;
}
</code></pre>
<pre><code class="lang-javascript">element.classList.add(<span class="hljs-string">'styledClass'</span>)
</code></pre>
<p>This example uses the <code>.add</code> property of <code>classList</code> to add the <code>styledClass</code> to the element. Assuming you wanted to remove the class from the element, you can easily do so using the <code>.remove</code> property in place of add.</p>
<h2 id="heading-use-innerhtml-with-caution">Use <code>innerHTML</code> with Caution</h2>
<p>The <code>innerHTML</code> property reads and parses HTML markup that you pass to it. This means it can read and run code in a script tag passed to it. And this can pose a security risk to your application.</p>
<p>Where possible, use the <code>innerText</code> or <code>textContent</code> property to render strings. But if you need to use <code>innerHTML</code>, be sure you're using it to insert content from trusted sources. Or sanitize and validate the provided content with a library like DOMPurify.</p>
<p>You can read <a target="_blank" href="https://www.freecodecamp.org/news/innerhtml-vs-innertext-vs-textcontent/#what-is-the-innerhtml-property">this freeCodeCamp article</a> to learn more about <code>innerHTML</code>.</p>
<h2 id="heading-write-readable-event-listeners">Write Readable Event Listeners</h2>
<p>Often you will pass two arguments to event listeners. The first is the event you're listening to and the second is the event handler (the function that fires when the event occurs).</p>
<p>To make your code easy to read and maintain, you can define the event handler function outside of the event listener. Then you can call it within the even listener, like in example 1 below:</p>
<pre><code class="lang-javascript">Example <span class="hljs-number">1</span> ✅

MyElement.addEventListener(<span class="hljs-string">'click'</span>, handleClick) 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params"></span>) </span>{ 
    <span class="hljs-comment">// your logic goes here.. </span>
} 

<span class="hljs-comment">// Example 2 ❌ </span>

myElement.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ 
    <span class="hljs-comment">// your logic goes here... </span>
})
</code></pre>
<p>Both are technically correct and will do the same thing. But example 1 is preferred because it's easier to read. Also, you can reuse the <code>handleClick</code> function if you need to. This helps you observe the DRY (Don't Repeat Yourself) principle.</p>
<h2 id="heading-use-event-delegation-to-handle-dom-events">Use Event Delegation to Handle DOM Events</h2>
<p>Event delegation is when you attach an event listener on a parent element to listen to events on its descendants. With this technique, you can reduce the number of event listeners to include in your code.</p>
<p>For example, assume you have five buttons inside a parent div:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"parent"</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-1"</span>&gt;</span>1st Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-2"</span>&gt;</span>2nd Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-3"</span>&gt;</span>3rd Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-4"</span>&gt;</span>4th Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn-5"</span>&gt;</span>5th Button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span> 
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>You can add an event listener to each of the five buttons to listen to a click. Or using event delegation, you can a single event on only the parent div:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> parentElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'parent'</span>) 

parentElement.addEventListener(<span class="hljs-string">'click'</span>, handleClick) 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params">event</span>) </span>{ 
  alert(event.target.id) 
}
</code></pre>
<p>In this example, the event to delegated to the parent element. And we're using <code>event.target.id</code> to get the actual button the user clicked. If you are curious, you can <a target="_blank" href="https://stackblitz.com/edit/js-r3qjyd?file=index.html,index.js">run the code on Stackblitz</a> to see how it works.</p>
<p>Event delegation help saves time improve performance. Imagine how this technique can come in handy when dealing with a large amount of dynamic content.</p>
<h2 id="heading-batch-dom-updates-with-fragment">Batch DOM Updates With Fragment</h2>
<p>Frequent updates to the DOM can affect the performance of your application. Try to reduce the number of updates where possible.</p>
<p>A useful feature you can use to batch updates is the <code>.createDocumentFragment</code> property. It allows you to group multiple updates before inserting them into the document. This reduces reflows and makes your code more effecient.</p>
<p>Example without Fragment:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> container = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'container'</span>)

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) { 
    <span class="hljs-keyword">const</span> listItem = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>)
    listItem.textContent = <span class="hljs-string">`Item <span class="hljs-subst">${i}</span>`</span>
    container.appendChild(listItem) 
}
</code></pre>
<p>This code updates with each iteration of the loop. That means the DOM will be update 1,000 times. There is a more efficient way of doing this with the code below that uses fragment.</p>
<p>Example with fragment:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> container = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'container'</span>) 
<span class="hljs-keyword">const</span> fragment = <span class="hljs-built_in">document</span>.createDocumentFragment()

<span class="hljs-comment">// Add multiple list items to the fragment </span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">1000</span>; i++) { 
    <span class="hljs-keyword">const</span> listItem = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>) 
    listItem.textContent = <span class="hljs-string">`Item <span class="hljs-subst">${i}</span>`</span> 
    fragment.appendChild(listItem)
} 

container.appendChild(fragment)
</code></pre>
<p>The code above appends the <code>listItem</code> to the <code>fragment</code> with each iteration of the loop. It only appends the child to the <code>container</code> element after the loop is done running. This means the DOM is updated only once instead of 1,000 times like before.</p>
<h2 id="heading-use-the-stoppropagation-method">Use the <code>stopPropagation</code> Method</h2>
<p>The <code>stopPropagation</code> method controls the flow of events in the DOM. By default, when an event occurs on an element, it bubbles (propagates) through its ancestors.</p>
<p>This event propagating behaviour can sometimes lead to unintended results. The <code>stopPropagation</code> method provides a way to stop the event from propagating to the parent and other ancestors.</p>
<p>Let's take a situation where you have a button inside a parent div. And you want to handle a click event on the button without registering the click on the div:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"button"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> containerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'container'</span>)
<span class="hljs-keyword">const</span> buttonElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'button'</span>)

containerDiv.addEventListener(<span class="hljs-string">'click'</span>, handleDivClick)
buttonElement.addEventListener(<span class="hljs-string">'click'</span>, handleBtnClick)

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleDivClick</span>(<span class="hljs-params"></span>) </span>{ 
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Div clicked'</span>)
} 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleBtnClick</span>(<span class="hljs-params">event</span>) </span>{ 
    event.stopPropagation()
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button clicked'</span>)
}
</code></pre>
<p>Without using the <code>stopPropagation</code> method, a click event on the button will also trigger a click event on the parent div. This means both event handlers will run.</p>
<p>But the <code>event.stopPropagation()</code> line in the code will prevent the <code>handleDivClick</code> function from running when a user clicks the button.</p>
<p>You can <a target="_blank" href="https://stackblitz.com/edit/js-wjmnd5?file=index.html,index.js">run the code on Stackblitz</a> to see how it works. Comment out the line with the <code>stopPropagation</code> method and see the difference.</p>
<h2 id="heading-test-your-dom-manipulation-code">Test Your DOM Manipulation Code</h2>
<p>When you write tests, you create scenarios that mimic user interactions or application states. You also verify that your application gives you the expected outcomes.</p>
<p>Testing your DOM manipulation code is a best practice because it will make your code reliable and easy to maintain. It also gives you confidence that your code behaves as expected, even as it evolves over time when you make changes and add features.</p>
<p>You can use testing frameworks and libraries available for JavaScript, such as Jest, Mocha, Jasmine, and others to automate testing your apps.</p>
<p>The following example uses the Jest framework to test DOM Manipulation code for adding a class to an element.</p>
<pre><code class="lang-javascript">test(<span class="hljs-string">'Adding a highlight class changes text color to red'</span>, <span class="hljs-function">() =&gt;</span> {
    myElement.classList.add(<span class="hljs-string">'highlight'</span>);
    expect(getComputedStyle(myElement).color).toBe(<span class="hljs-string">'red'</span>);
});
</code></pre>
<p>Adding the <code>highlight</code> class is expected to change the text color to red. If the test passes, it means your DOM manipulation code works as expected. If not, you will need to figure out what figure out what's wrong and fix the issue.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article you've learned ten best practices to keep in mind when working with the DOM. Some of them are general while others are situation specific. By using these best practices in your workflow, you will be building your web applications with a code base that is easy to maintain.</p>
<p>If you want to dive deep into DOM manipulation, <a target="_blank" href="https://www.freecodecamp.org/news/the-javascript-dom-manipulation-handbook/">I wrote a whole handbook</a> that covers the subject in depth.</p>
<p>Thanks for reading. And happy coding! For more in-depth tutorials, feel free to <a target="_blank" href="https://www.youtube.com/@DevAfterHours">subscribe to my YouTube channel</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Manipulate the DOM in JavaScript – Most Commonly Used Techniques ]]>
                </title>
                <description>
                    <![CDATA[ Hi everyone! In this article, I’m going to cover everything you need to know about manipulating the DOM. Basically, each Element object in the DOM has properties and methods that you can use to interact with that element. The following are the most c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-document-object-model-explained/</link>
                <guid isPermaLink="false">66bd9178621c718d60a3106d</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Nathan Sebhastian ]]>
                </dc:creator>
                <pubDate>Thu, 07 Dec 2023 22:19:23 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/12/js-dom-manipulation-1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Hi everyone! In this article, I’m going to cover everything you need to know about manipulating the DOM.</p>
<p>Basically, each <code>Element</code> object in the DOM has properties and methods that you can use to interact with that element.</p>
<p>The following are the most common and practical ways you might want to manipulate the <code>Element</code> object:</p>
<ol>
<li><a class="post-section-overview" href="#heading-change-the-content-of-an-element">Change the Content of an Element</a></li>
<li><a class="post-section-overview" href="#heading-manipulate-the-class-attribute">Manipulate the Class Attribute</a></li>
<li><a class="post-section-overview" href="#heading-setting-css-styles-using-javascript">Setting CSS Styles Using JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-create-add-and-remove-elements">Create, Add, and Remove Elements</a></li>
<li><a class="post-section-overview" href="#heading-insert-element-at-a-specific-position">Insert Element at a Specific Position</a></li>
<li><a class="post-section-overview" href="#heading-manipulating-element-attributes">Manipulating Element Attributes</a></li>
<li><a class="post-section-overview" href="#heading-manipulating-data-attributes">Manipulating Data Attributes</a></li>
</ol>
<p>Manipulating the DOM seems complex in theory, but as you’ll see in this article, there are a few methods that you’ll use over and over again in many scenarios.</p>
<p>Once you know about these methods, you will have leveled up your skill in DOM manipulation. Let’s begin!</p>
<h2 id="heading-change-the-content-of-an-element">Change the Content of an Element</h2>
<p>You can change the value or content of an element by setting the <code>innerText</code> property of that element.</p>
<p>For example, suppose you have a paragraph element as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"myParagraph"</span>&gt;</span>This is a paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Next, you select the element and change its <code>innerText</code> value like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.myParagraph'</span>);

p.innerText = <span class="hljs-string">'A new day is dawning'</span>;
</code></pre>
<p>The <code>p</code> element would have its value changed as you see below:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"myParagraph"</span>&gt;</span>A new day is dawning<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>And that’s how you change the value of an element.</p>
<h2 id="heading-manipulate-the-class-attribute">Manipulate the Class Attribute</h2>
<p>You can add a new <code>class</code> attribute to an <code>Element</code> by using the <code>add()</code> method of the <code>classList</code> object:</p>
<pre><code class="lang-js">Element.classList.add(<span class="hljs-string">'myClass'</span>);
</code></pre>
<p>You can remove a class using the <code>remove()</code> method:</p>
<pre><code class="lang-js">Element.classList.remove(<span class="hljs-string">'myClass'</span>);
</code></pre>
<p>The <code>classList</code> object is a collection object that you can use to manipulate the <code>class</code> attribute of an <code>Element</code>.</p>
<p>You can’t directly edit the <code>classList</code> property because it’s a read-only property. But you can use its methods to change the element classes.</p>
<p>To replace an existing class with a new class, use the <code>replace()</code> method:</p>
<pre><code class="lang-js">Element.classList.replace(<span class="hljs-string">'oldClass'</span>, <span class="hljs-string">'newClass'</span>);
</code></pre>
<p>There’s also the <code>toggle()</code> method, which works like a switch: adds a class if it’s not there, removes a class if it’s there.</p>
<pre><code class="lang-js">Element.classList.toggle(<span class="hljs-string">'myClass'</span>);
</code></pre>
<p>To check if an element contains a specific class, use the <code>contains()</code> method and pass the class you want to check as a string:</p>
<pre><code class="lang-js">Element.classList.contains(<span class="hljs-string">'myClass'</span>);
</code></pre>
<p>The method returns <code>true</code> when the class is specified. Otherwise it returns <code>false</code>.</p>
<h2 id="heading-setting-css-styles-using-javascript">Setting CSS Styles Using JavaScript</h2>
<p>Since you’ve learned how to set and remove classes from an element, you can control the style of an element by adding or removing classes that change the style rules applied to an element.</p>
<p>For example, you might have the following style rules in your CSS code:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.color-primary</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#007bff</span>;
}

<span class="hljs-selector-class">.color-secondary</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#6c757d</span>;
}

<span class="hljs-selector-class">.bold</span> {
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">700</span>;
}
</code></pre>
<p>If you have an element with the <code>color-primary</code> class applied, you can replace it with <code>color-secondary</code> class, or add the <code>bold</code> class. </p>
<p>Suppose you have a paragraph element as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"myParagraph"</span>&gt;</span>A new day is dawning<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>Here’s how you change the style using classes:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.myParagraph'</span>);

<span class="hljs-comment">// add a class to the element</span>
p.classList.add(<span class="hljs-string">'color-primary'</span>);

<span class="hljs-comment">// replace a class</span>
p.classList.replace(<span class="hljs-string">'color-primary'</span>, <span class="hljs-string">'color-secondary'</span>);

<span class="hljs-comment">// remove a class</span>
p.classList.remove(<span class="hljs-string">'color-secondary'</span>);
</code></pre>
<p>At times, you might need to apply CSS directly to the DOM element you selected.</p>
<p>The <code>Element</code> object provides you with the <code>style</code> property which controls the inline style of the element.</p>
<p>For example, you can change the font weight of an element using the <code>Element.style.fontWeight</code> property like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.myParagraph'</span>);

p.style.fontWeight = <span class="hljs-string">'700'</span>; <span class="hljs-comment">// set font weight</span>
p.style.textTransform = <span class="hljs-string">'uppercase'</span>; <span class="hljs-comment">// set to uppercase</span>
p.style.color = <span class="hljs-string">'#007bff'</span>; <span class="hljs-comment">// set color</span>
</code></pre>
<p>You can change the border style of an element as follows:</p>
<pre><code class="lang-js">p.style.border = <span class="hljs-string">'1px solid black'</span>;
</code></pre>
<p>The <code>style</code> property uses the camelCase instead of the hyphen-case, so <code>font-weight</code> becomes <code>fontWeight</code> and <code>text-transform</code> becomes <code>textTransform</code>.</p>
<p>And now you know how to set CSS styles using JavaScript. I would recommend that you change element styles by adding and removing classes because it’s more maintainable and follows the common approach.</p>
<p>Only access the <code>style</code> property if you won’t use the same style anywhere else.</p>
<h2 id="heading-create-add-and-remove-elements">Create, Add, and Remove Elements</h2>
<p>Besides creating a DOM tree out of your HTML file, you also have the ability to create DOM elements programmatically using JavaScript.</p>
<p>This is possible because the <code>document</code> object also has the <code>createElement()</code> method, which allows you to create any <code>Element</code> object, which is essentially the tags you write in your HTML file.</p>
<p>For example, you can create a paragraph element like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>);
</code></pre>
<p>After you create that element, you can add some content to it using the <code>innerText</code> property:</p>
<pre><code class="lang-js">p.innerText = <span class="hljs-string">'This paragraph is created using JavaScript'</span>;
</code></pre>
<p>Now you need to add it to the existing DOM tree so that it appears on the screen. You can attach the element anywhere inside your existing tree structure.</p>
<p>Suppose you want to add the paragraph to the <code>body</code> tag. Then you need to use the <code>querySelector()</code> method to select the <code>body</code>, and call the <code>append()</code> method on the element:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>);

p.innerText = <span class="hljs-string">'This paragraph is created using JavaScript'</span>;

<span class="hljs-keyword">const</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>);

body.append(p);
</code></pre>
<p>The paragraph will be added as a child of the <code>body</code> tag as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This paragraph is created using JavaScript<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>If you want to remove an element, you can call the <code>remove()</code> method from the element you want to remove.</p>
<p>This code will remove the paragraph element:</p>
<pre><code class="lang-js">p.remove();
</code></pre>
<h2 id="heading-insert-element-at-a-specific-position">Insert Element at a Specific Position</h2>
<p>The <code>append()</code> method that we explored above will insert a new element as the last child of the parent element.</p>
<p>If you want to insert the element at a specific position, you can use the <code>insertBefore()</code> method.</p>
<p>Let’s see an easy example. Suppose you have an HTML content as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>The first paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>To insert an element before the first paragraph, you need to call the <code>insertBefore()</code> method from the parent element (which is the <code>body</code> tag) and pass two arguments to it:</p>
<ol>
<li>The new element you want to add</li>
<li>The sibling element before which the new element is inserted</li>
</ol>
<p>Here’s an example of creating a second paragraph and inserting it before the first paragraph:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> p2 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>);

p2.innerText = <span class="hljs-string">'The second paragraph'</span>;

<span class="hljs-keyword">let</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>);
<span class="hljs-keyword">let</span> p1 = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#first'</span>);

body.insertBefore(p2, p1);
</code></pre>
<p>As a result of running the script above, the second paragraph will be inserted before the first paragraph:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>The second paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>The first paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>Keep in mind that the DOM doesn’t provide an <code>insertAfter</code> method, because it’s not needed.</p>
<p>You use the <code>append()</code> method to insert an element at the last position, and if you want to control the position, use the <code>insertBefore()</code> method.</p>
<h2 id="heading-manipulating-element-attributes">Manipulating Element Attributes</h2>
<p>The <code>classList</code> object only provide methods to change the <code>class</code> of an element. If you want to change other attributes like <code>id</code>, <code>href</code>, or <code>src</code>, you can use the <code>setAttribute()</code> method.</p>
<p>The <code>setAttribute()</code> method accepts two arguments:</p>
<ol>
<li>The name of the attribute to set</li>
<li>The value of the attribute to set</li>
</ol>
<p>For example, here’s how to set the <code>src</code> attribute of an <code>img</code> tag:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"profile-pic"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"feature-image.png"</span> /&gt;</span>
</code></pre>
<p>Select the <code>img</code> element using <code>querySelector()</code>, then call the <code>setAttribute()</code> method on the element:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> img = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#profile-pic'</span>);

img.setAttribute(<span class="hljs-string">'src'</span>, <span class="hljs-string">'new-image.jpg'</span>);
</code></pre>
<p>The <code>src</code> attribute value would be changed as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"profile-pic"</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"new-image.jpg"</span> /&gt;</span>
</code></pre>
<p>If you want to the an attribute’s value, you can use the <code>getAttribute()</code> method.</p>
<p>Pass the attribute you want to check as an argument to the method. If the attribute is set, the method returns the value of that attribute as a string. If not, it returns <code>null</code>:</p>
<pre><code class="lang-js">img.getAttribute(<span class="hljs-string">'src'</span>); <span class="hljs-comment">// new-image.jpg</span>
img.getAttribute(<span class="hljs-string">'href'</span>); <span class="hljs-comment">// null</span>
</code></pre>
<p>You can use both <code>setAttribute()</code> and <code>getAttribute()</code> methods to interact with any HTML attributes.</p>
<p>If you want to delete an attribute, use the <code>removeAttribute()</code> method:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> img = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#profile-pic'</span>);

<span class="hljs-comment">// Delete the src attribute</span>
img.removeAttribute(<span class="hljs-string">'src'</span>);
</code></pre>
<h2 id="heading-manipulating-data-attributes">Manipulating Data Attributes</h2>
<p>The data attribute is used to store extra information on HTML elements. How you use the data is up to you.</p>
<p>Suppose you have an HTML tag as follows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"intro"</span> <span class="hljs-attr">data-attribute-theme</span>=<span class="hljs-string">"light"</span> <span class="hljs-attr">data-session</span>=<span class="hljs-string">"2022"</span>&gt;</span>
  Hello World!
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>You can access the data attributes from the <code>dataset</code> property of the element above like this:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Select the div</span>
<span class="hljs-keyword">let</span> myDiv = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#intro'</span>);

<span class="hljs-comment">// Access the dataset property</span>
<span class="hljs-built_in">console</span>.log(myDiv.dataset.session) <span class="hljs-comment">// 2022</span>

<span class="hljs-comment">// Use camelCase when your data attribute is more than one word</span>
<span class="hljs-built_in">console</span>.log(myDiv.dataset.attributeTheme) <span class="hljs-comment">// light</span>
</code></pre>
<p>If you want to change the attribute value, you can reassign the right <code>dataset</code> property to a new value directly:</p>
<pre><code class="lang-js"><span class="hljs-comment">// Select the div</span>
<span class="hljs-keyword">let</span> myDiv = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#intro'</span>);

<span class="hljs-comment">// Change the value of a data attribute</span>
myDiv.dataset.session = <span class="hljs-string">'2023'</span>
</code></pre>
<p>If you want to delete the data attribute, use the <code>removeAttribute()</code> method similar to how you delete a regular attribute:</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> myDiv = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#intro'</span>);

<span class="hljs-comment">// Remove data-session attribute</span>
myDiv.removeAttribute(<span class="hljs-string">'data-session'</span>);

<span class="hljs-comment">// Remove data-attribute-theme attribute</span>
myDiv.removeAttribute(<span class="hljs-string">'data-attribute-theme'</span>);
</code></pre>
<p>And that’s how you manipulate the data attribute using JavaScript.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>And that's all for now about DOM element manipulations. At this point, I hope you can see why JavaScript is required to build a modern web application. It allows you to interact and change the content that exists in your website.</p>
<p>This enables a whole lot of dynamic changes to the website you created.</p>
<p>If you enjoyed this article and want to take your JavaScript skills to the next level, I recommend you check out my new book <em>Beginning Modern JavaScript</em> <a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G">here</a>.</p>
<p><a target="_blank" href="https://www.amazon.com/dp/B0CQXHMF8G"><img src="https://www.freecodecamp.org/news/content/images/2024/01/beginning-js-cover.png" alt="beginning-js-cover" width="600" height="400" loading="lazy"></a></p>
<p>The book is designed to be easy to understand and accessible to anyone looking to learn JavaScript. It provides a step-by-step gentle guide that will help you understand how to use JavaScript to create a dynamic application.</p>
<p>Here's my promise: <em>You will actually feel like you understand what you're doing with JavaScript.</em></p>
<p>Until next time!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How the Document Object Model Works in JavaScript – DOM Tutorial for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ The Document Object Model (DOM) is an essential part of web development. It provides a way for programmers to interact with and manipulate the structure of a website.  With the help of the DOM, developers can access and change the different parts of ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-dom/</link>
                <guid isPermaLink="false">66bd90522384aa6dc0878d5f</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Boateng Dickson ]]>
                </dc:creator>
                <pubDate>Thu, 19 Jan 2023 15:21:29 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/JavaScript-DOM-cover-image1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>The Document Object Model (DOM) is an essential part of web development. It provides a way for programmers to interact with and manipulate the structure of a website. </p>
<p>With the help of the DOM, developers can access and change the different parts of a webpage. This allows them to create dynamic and interactive websites, where user interactions can trigger changes in the page's layout and content. </p>
<p>Understanding the DOM is crucial for creating responsive and user-friendly websites. So in this article, we will delve deeper into what the DOM can do and how you can use it in JavaScript.</p>
<h2 id="heading-what-is-the-dom">What is the DOM?</h2>
<p>The DOM, or Document Object Model, is like a map of a website. Just like how a map shows you where all the streets and buildings are in a city, the DOM shows you where everything is on a website. </p>
<p>The DOM helps your computer understand the different parts of a website and how they are put together. </p>
<p>Just like you can use a map to find your way around a city, programmers can use the DOM to find different parts of a website and change their properties. For example, they can make a button change color when a user hovers over it or make pictures move around on the screen.</p>
<p>The DOM is like a big puzzle. But using JavaScript, we can move the puzzle pieces around and make a website look and work however we want it to work.</p>
<h2 id="heading-the-dom-javascript">The DOM + JavaScript</h2>
<p>JavaScript is a programming language that helps us interact with the DOM. The DOM and JavaScript are like two friends that work together to make websites cool and interactive. Again, the DOM is like a big map that shows where all the different parts of the website are located.</p>
<p>On the other hand, JavaScript is like a magic wand that can change a website by using the map (DOM) to find the different parts of the website. It can make a button change color when you click on it or make a picture move to a different spot on the page. </p>
<p>Together, the DOM and JavaScript make the website come alive and respond to what you do, like moving your mouse or clicking on a button. </p>
<p>In summary, the DOM is like a map that shows where everything is and JavaScript is like a magic wand that can change things on that map.</p>
<h2 id="heading-dom-structure-understanding-the-dom-tree">DOM Structure – Understanding the DOM Tree</h2>
<p>Imagine a website is like a big book, and each page in that book represents a different part of the website. The DOM tree is like a table of contents for that book. It shows you all the different parts of the website, and how they are organized. </p>
<p>Each part of the website is called an "element" and these elements are arranged in a tree-like structure. </p>
<p>The top of the tree is called the "root" and it represents the entire website. From there, the tree branches out into different sections, like the headings, paragraphs, images, and others that make up the entire website.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/DOM-tree-5.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration of the DOM tree</em></p>
<p>Just like how the table of contents in a book helps you find specific pages, the DOM tree helps computers find specific elements on a website. In addition, it allows developers to access and change those elements, so they can make the website interactive. </p>
<p>In short, the DOM tree represents the structure of a website in a way that computers can understand. Developers can use it to access and manipulate different elements in that structure to create dynamic web pages.</p>
<h2 id="heading-how-to-access-the-dom">How to Access the DOM</h2>
<p>Accessing elements in the DOM means finding specific parts of a website and changing or manipulating them. </p>
<p>To access an element on a website, you need to know the specific element you want to access. </p>
<p>JavaScript provides different methods to access the elements in the DOM, such as <code>getElementById</code>, <code>getElementsByTagName</code>, <code>querySelector</code>, and <code>querySelectorAll</code>. </p>
<p>These methods allow you to find an element based on its <code>id</code>, <code>tagname</code>, or <code>classname</code> and select it for manipulation. </p>
<p>For example, you can access a button on a webpage and change its text or color when a user clicks on it. Or, you can access an image on a webpage and change it to a different image when a user hovers over it. </p>
<p>Here's an example of how you might use the DOM to access an element on a webpage: </p>
<p>Let's say you have a webpage that displays a list of students and you want to change the background color of a specific student when they are clicked. </p>
<p>You can use the DOM method <code>getElementById</code> to access the specific element that represents the student and then use the <code>style</code> property in JavaScript to change the background color of that element.</p>
<p>Here's how that might look:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"student-list"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"student-1"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"student"</span>&gt;</span>John<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"student-2"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"student"</span>&gt;</span>Alice<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"student-3"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"student"</span>&gt;</span>Bob<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.student</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">40px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">cursor</span>: pointer;
}
<span class="hljs-selector-class">.student</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#f1f1f1</span>;
}
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> student1 = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"student-1"</span>);

student1.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  student1.style.backgroundColor = <span class="hljs-string">"lightblue"</span>;
});
</code></pre>
<p>In this example, JavaScript is using the <code>getElementById</code> method to select the element with the id "student-1" and it changes its <code>backgroundColor</code> property to "light blue" when you click on it.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Document_4.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Similarly, you can use <code>getElementsByClassName</code> to select all elements with a specific class and <code>querySelector</code> to select an element based on a CSS selector.</p>
<p>This is just a basic example, but it illustrates how you can use the DOM to access specific elements on a webpage and change their properties in response to user interaction.</p>
<h2 id="heading-how-to-add-remove-and-modify-dom-elements">How to Add, Remove, and Modify DOM Elements</h2>
<p>Adding, removing, and modifying elements in the DOM refers to adding new elements to a webpage, removing existing elements, and changing the properties of existing elements.</p>
<p>For example, if you want to add a new button to a webpage, you would use JavaScript to create a new element and then use the DOM to add that element to the webpage. Similarly, if you want to remove an element, you would use the DOM to find the element and then delete it.</p>
<p>Modifying elements also involves making changes to the properties of an existing element. For example, you could use the DOM to change the text inside a button.</p>
<p>Here’s how you can express this in code.:</p>
<pre><code class="lang-html">    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"wrapper"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn-wrapper"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"create-btn"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span>&gt;</span>Create new button<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-css"><span class="hljs-selector-class">.btn-wrapper</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">gap</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
}
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> createButton = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"create-btn"</span>);
<span class="hljs-keyword">let</span> wrapper = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"wrapper"</span>);

createButton.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> newButton = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"button"</span>);
  newButton.innerHTML = <span class="hljs-string">"Click me"</span>;
  wrapper.appendChild(newButton);
});
</code></pre>
<p>In the above example, we are creating a new button element and setting the text inside the button to "Click me". Then we're using the <code>appendChild</code> method to add this new button element to the webpage.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Document.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-recap">Recap</h2>
<p>The Document Object Model (DOM) is an essential tool for creating interactive, dynamic web pages using JavaScript. It allows developers to access and manipulate the contents of a webpage in real time. </p>
<p>Understanding the DOM tree and how to access, add, remove, and modify elements is crucial for JavaScript developers.</p>
<p>We've seen how the DOM represents a webpage as a tree of objects and how we can use different methods like <code>getElementById</code>, <code>getElementsByTagName</code>, <code>querySelector</code>, and <code>querySelectorAll</code> to access specific elements on a webpage. With these methods, we can change the content, style, or layout of a webpage after it has loaded in the browser. </p>
<p>Additionally, we've seen how to add new elements to a webpage, remove existing elements, and change the properties of existing elements.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope this article has given you a better understanding of the Document Object Model and how to use it to create dynamic web pages. </p>
<p>Remember that the DOM is a powerful tool that you can use to create amazing websites, so don't be afraid to experiment and try new things.</p>
<p>Thanks for reading! Kindly share this article and follow me on  Twitter <a target="_blank" href="https://twitter.com/alege_dev">@alege_dev</a> for updates on future posts.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Event Bubbling in JavaScript – How Event Propagation Works with Examples ]]>
                </title>
                <description>
                    <![CDATA[ By Dillion Megida HTML elements receive different types of events, from click, to blur, to scroll, and so on.  One behavior these events have in common is Event Bubbling. I'll explain what this behavior means in this article. I also made a video vers... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/event-bubbling-in-javascript/</link>
                <guid isPermaLink="false">66d84eedda89a73e2ddf5790</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 31 Oct 2022 21:04:17 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/10/1.-event-bubbling-js.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dillion Megida</p>
<p>HTML elements receive different types of events, from click, to blur, to scroll, and so on. </p>
<p>One behavior these events have in common is Event Bubbling. I'll explain what this behavior means in this article.</p>
<p>I also made a video version of this article which <a target="_blank" href="https://www.youtube.com/watch?v=KaHZdW02Tg0">you can watch here</a>.</p>
<h2 id="heading-what-is-event-bubbling">What is Event Bubbling?</h2>
<p>Event Bubbling is a concept in the DOM (Document Object Model). It happens when an element receives an event, and that event bubbles up (or you can say is transmitted or propagated) to its parent and ancestor elements in the DOM tree until it gets to the root element.</p>
<p>This is the default behavior of events on elements unless you stop the propagation <a class="post-section-overview" href="#how-to-stop-event-bubbling">which I'llexplain at the end of this article</a></p>
<p>Let's look at an example so I can better explain how event bubbling works.</p>
<p>The HTML:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Click Me!<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>The CSS:</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">background-color</span>: pink;
}

<span class="hljs-selector-tag">div</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">background-color</span>: green;
  <span class="hljs-attribute">width</span>: max-content;
}

<span class="hljs-selector-tag">span</span> {
  <span class="hljs-attribute">display</span>: block;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">background-color</span>: blue;
}
</code></pre>
<p>The result:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-256.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The <strong>button</strong> is a child of the <strong>span</strong>, which in turn is a child of the <strong>div</strong>, and the div is a child of the <strong>body</strong>. The DOM tree would look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-263.png" alt="Image" width="600" height="400" loading="lazy">
<em>DOM tree for this interaction</em></p>
<p>When you click the <strong>button</strong>, you can think of it like you're also clicking the <strong>span</strong> (the blue background). This is because the button is a child of the span. </p>
<p>It's also the same thing with the <strong>div</strong> and the <strong>body</strong>. When you click the button, it's just like you're also clicking the span, div, and body because they are the button's ancestors. This is the idea of event bubbling.</p>
<p>An event doesn't stop at the direct element that receives it. The event bubbles up to its ancestors, until it gets to the root element.</p>
<p>So if the button receives a <strong>click</strong> event, for example, the <code>span</code>, <code>div</code>, and <code>body</code> (up until <strong>html</strong>, the root element) respectively receive that event:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/10/image-264.png" alt="Image" width="600" height="400" loading="lazy">
<em>Illustration showing how event bubbling works</em></p>
<p>Also, if you click on the blue box (span), the button doesn't receive the click event as it is not a parent or ancestor or the span. But, the div, body, and HTML would receive the event.</p>
<p>The same thing happens if you click on the div – the event is propagated to the body and html element.</p>
<h2 id="heading-how-to-handle-events-that-bubble">How to Handle Events that Bubble</h2>
<p>The "Event Bubbling" behavior makes it possible for you to handle an event in a parent element instead of the actual element that received the event.</p>
<p>The pattern of handling an event on an ancestor element is called Event Delegation. You can <a target="_blank" href="https://www.freecodecamp.org/news/event-delegation-javascript/">read more about it here</a>.</p>
<p>Let's create some event listeners and handlers:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> body = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"body"</span>)[<span class="hljs-number">0</span>]
<span class="hljs-keyword">const</span> div = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"div"</span>)[<span class="hljs-number">0</span>]
<span class="hljs-keyword">const</span> span = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"span"</span>)[<span class="hljs-number">0</span>]
<span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"button"</span>)[<span class="hljs-number">0</span>]

body.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"body was clicked"</span>)
})

div.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"div was clicked"</span>)
})

span.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"span was clicked"</span>)
})

button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"button was clicked"</span>)
})
</code></pre>
<p>Here, we've selected the <code>body</code>, <code>div</code>, <code>span</code>, and <code>button</code> elements from the DOM. Then we added the <code>click</code> event listeners to each of them and a handler function that logs "body was clicked", "div was clicked", "span was clicked", and "button was clicked", respectively.</p>
<p>What happens on the console when you click on the pink background (which is the body) is:</p>
<pre><code class="lang-bash">body was clicked
</code></pre>
<p>When you click on the green background (which is the div), the console shows:</p>
<pre><code class="lang-bash">div was clicked
body was clicked
</code></pre>
<p>The "click" event on the body element is triggered even though the div element was the target element clicked because the "click" event bubbled from the div to the body.</p>
<p>When you click on the blue background (which is the span), the console shows:</p>
<pre><code class="lang-bash">span was clicked
div was clicked
body was clicked
</code></pre>
<p>And, lastly, when you click on the button, the console shows:</p>
<pre><code class="lang-bash">button was clicked
span was clicked
div was clicked
body was clicked
</code></pre>
<h2 id="heading-how-to-stop-event-bubbling">How to Stop Event Bubbling</h2>
<p>Event Bubbling is a default behavior for events. But in some cases, you might want to prevent this. </p>
<p>Let's say, for example, from our HTML code, that you want the div to open a modal when it is clicked. For the button, on the other hand, you want it to make an API request when it is clicked.</p>
<p>In this case, you may not want the modal to open when you click the button. You might want the modal to only open when you actually click it (and not when you click any of its children). This is where preventing event propagation comes in.</p>
<p>To prevent event bubbling, you use the <code>stopPropagation</code> method of the event object.</p>
<p>When handling events, an <code>event</code> object is passed to the handling function:</p>
<pre><code class="lang-js">button.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  <span class="hljs-comment">// do anything with the event object</span>
}
</code></pre>
<p>The <code>event</code> object contains properties that have information about the event that was triggered and the element it was triggered on. This object also contains methods – one of which is <code>stopPropagation()</code>.</p>
<p>The <code>stopPropagation</code> method of an event prevents the event from propagating to the parents and ancestors of the element the event was triggered on. </p>
<p>We can use this in the JavaScript code from above:</p>
<pre><code class="lang-js">body.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"body was clicked"</span>)
})

div.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"div was clicked"</span>)
})

span.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"span was clicked"</span>)
})

button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  event.stopPropagation()
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"button was clicked"</span>)
})
</code></pre>
<p>With this, when you click on the button, all you get in the console is:</p>
<pre><code class="lang-bash">button was clicked
</code></pre>
<p>The button's parents and ancestors do not receive the click event as it doesn't bubble up from the button.</p>
<p>You can also stop the bubbling from a different element like this:</p>
<pre><code class="lang-js">body.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"body was clicked"</span>)
})

div.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"div was clicked"</span>)
})

span.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  event.stopPropagation()
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"span was clicked"</span>)
})

button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"button was clicked"</span>)
})
</code></pre>
<p>With the <code>stopPropagation()</code> called on the span's event listener, and the button clicked, on the console you get:</p>
<pre><code class="lang-js">button was clicked
span was clicked
</code></pre>
<p>The event bubbles from the button to the span but stops there because the propagation is stopped at this point.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>When elements receive events, such events propagate to their parents and ancestors upward in the DOM tree. This is the concept of <strong>Event Bubbling</strong>, and it allows parent elements to handle events that occur on their children's elements.</p>
<p>Event objects also have the <code>stopPropagation</code> method which you can use to stop the bubbling of an event. This is useful in cases where you want an element to receive a click event only when it is clicked and not when any of its children elements are clicked.</p>
<p><code>stopPropagation</code> and <code>preventDefault</code> are methods of the event object for stopping default behaviors. Here is an article on <a target="_blank" href="https://www.freecodecamp.org/news/manage-default-behavior-in-browser/">the difference between these methods</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the DOM? A Behind-the-Scenes Guide ]]>
                </title>
                <description>
                    <![CDATA[ Understanding how the DOM and events work in JavaScript is key if you want to be an effective front end developer. In this article, you'll learn what the DOM is and how it works. What is the DOM? DOM stands for Document Object Model. It's the interfa... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-dom-in-javascript/</link>
                <guid isPermaLink="false">66d45f76ffe6b1f641b5fa13</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kedar Makode ]]>
                </dc:creator>
                <pubDate>Fri, 30 Sep 2022 14:50:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/What-is-DOM-and-Events--in-JavaScipt--2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Understanding how the DOM and events work in JavaScript is key if you want to be an effective front end developer.</p>
<p>In this article, you'll learn what the DOM is and how it works.</p>
<h2 id="heading-what-is-the-dom">What is the DOM?</h2>
<p>DOM stands for Document Object Model. It's the interface between JavaScript and the web browser.</p>
<p>With the help of the DOM, you can write JavaScript to create, modify, and delete HTML elements, set styles, classes and attributes, and listen and respond to events.</p>
<p>The DOM tree is generated from an HTML document, which you can then interact with. The DOM is a very complex API which has methods and properties to interact with the DOM tree.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/Frame-70-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>Illustration of the DOM</em></p>
<p>You can visualize the DOM tree <a target="_blank" href="https://fritscher.ch/dom-css/">here</a>.</p>
<h2 id="heading-how-the-dom-works-behind-the-scenes">How the DOM Works – Behind the Scenes</h2>
<p>The DOM is organized in a really clever manner. The parent element is called the EventTarget. You can understand better how it works with the help of the below diagram:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/DOM-behind-the-scene-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The EventTarget interface is implemented by objects which can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface. <strong>Element</strong>, and its children, as well as <strong>Document</strong> and <strong>Window</strong> are the most common event targets, but other objects can be event targets, too.</p>
<p>Window represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object. Even the document object (of the HTML DOM) is a property of the window object.</p>
<pre><code class="lang-js"><span class="hljs-built_in">window</span>.document.getElementById(<span class="hljs-string">"header"</span>);

<span class="hljs-comment">// Both are same</span>

<span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"header"</span>);
</code></pre>
<p>Nodes are in the DOM aka Document Object model. In the DOM, all parts of the document, such as elements, attributes, text, and so on are organized in a hierarchical tree-like structure that consists of parents and children. These individual parts of the document are known as nodes.</p>
<p>The Node in the above diagram is represented by a JavaScript object. We mostly work with the document which has most commonly used methods like document.queryselector(), document.getElementBy Id(), and so on.</p>
<p>Now we will take a look at the document.</p>
<h2 id="heading-how-to-select-create-and-delete-elements-using-the-dom">How to Select, Create, and Delete Elements Using the DOM</h2>
<p>With the help of the DOM, we can select, delete, and create element in JavaScript.</p>
<h3 id="heading-how-to-select-elements">How to Select Elements</h3>
<p>There are multiple ways we can select HTML elements in JavaScript. These are the methods we'll look at here:</p>
<ul>
<li><p>document.getElementById();</p>
</li>
<li><p>document.getElementByClassName();</p>
</li>
<li><p>document.getElementByTagName();</p>
</li>
<li><p>document.querySelector();</p>
</li>
<li><p>document.querySelectorAll();</p>
</li>
</ul>
<h4 id="heading-how-to-use-the-documentgetelementbyid-method">How to use the <code>document.getElementById()</code> method</h4>
<p>The <code>getElementById()</code> method returns an element whose id matches a passed string. Since the ids of HTML elements are supposed to be unique, this is a faster way to select an element with ids.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"IDName"</span>);
<span class="hljs-built_in">console</span>.log(ele); <span class="hljs-comment">// This will log the whole HTML element</span>
</code></pre>
<h4 id="heading-how-to-use-the-documentgetelementbyclassname-method">How to use the <code>document.getElementByClassName()</code> method</h4>
<p>The <code>document.getElementByClassName()</code> method returns an <code>HTMLCollection</code> of elements that match the passed class's name. We can search for multiple class names by passing the class names separated by whitespaces. It will return a live HTMLCollection.</p>
<p>So what does it mean that the HTMLCollection is "live"? Well, it means that once we get the HTMLCollection for a class name, if we add an element with the same class name, then the HTMLCollection gets updated automatically.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.getElementByClassName(<span class="hljs-string">"ClassName"</span>);
<span class="hljs-built_in">console</span>.log(ele); <span class="hljs-comment">// Logs Live HTMLCollection</span>
</code></pre>
<h4 id="heading-how-to-use-the-documentgetelementbytagname-method">How to use the <code>document.getElementByTagName();</code> method</h4>
<p>The <code>document.getElementByTagName()</code> method returns the HTMLCollection of elements that match the passed tag name. It can be called on any HTML element. It returns an HTMLCollection which is a live collection.</p>
<p>Example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> paragraph = <span class="hljs-built_in">document</span>.getElementByTagName(<span class="hljs-string">"p"</span>);
<span class="hljs-keyword">const</span> heading = <span class="hljs-built_in">document</span>.getElementByTagName(<span class="hljs-string">"h1"</span>);

<span class="hljs-built_in">console</span>.log(paragraph); <span class="hljs-comment">// p element HTMLCollection</span>
<span class="hljs-built_in">console</span>.log(heading); <span class="hljs-comment">// h1 element HTMLCollection</span>
</code></pre>
<h4 id="heading-how-to-use-the-documentqueryselector-method">How to use the document.querySelector() method</h4>
<p>The <code>document.querySelector()</code> method returns the first element that matches the passed selector. Now here, we can pass classname, id, and tagname. Take a look at the below example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> id = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#idname"</span>); <span class="hljs-comment">// using id</span>
<span class="hljs-keyword">const</span> classname = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".classname"</span>); <span class="hljs-comment">// using class</span>
<span class="hljs-keyword">const</span> tag = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"p"</span>); <span class="hljs-comment">// using tagname</span>
</code></pre>
<p>Rules for selection:</p>
<ul>
<li><p>When selecting using class, use (.) at the start. For example (".classname")</p>
</li>
<li><p>When selecting using id, use (#) at the start. For example ("#id")</p>
</li>
<li><p>When selecting using a tag, simply select directly. For example ("p")</p>
</li>
</ul>
<h4 id="heading-how-to-use-the-documentqueryselectorall-method">How to use the document.querySelectorAll() method</h4>
<p>The <code>document.querySelectorAll()</code> method is an extension of the <code>querySelector</code> method. This method returns <strong>all</strong> the elements that match the passed selector. It returns the Nodelist collection which is not live.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"p"</span>);
<span class="hljs-built_in">console</span>.log(ele); <span class="hljs-comment">// return nodelist collection of p tag</span>
</code></pre>
<p><strong>NOTE</strong>: HTMLCollection is a live collection, while the Nodelist collection is a static collection.</p>
<h3 id="heading-how-to-create-elements">How to Create Elements</h3>
<p>You can create HTML elements in JavaScript and add them to HTML dynamically. You can create any HTML element with <code>document.createElement()</code> by passing the tag name in parenthesis.</p>
<p>After you create the element, you can add the classname, attributes and textcontent to that element.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"a"</span>);
ele.innerText = <span class="hljs-string">"Click Me"</span>;
ele.classList.add(<span class="hljs-string">"text-left"</span>);
ele.setAttribute(<span class="hljs-string">"href"</span>, <span class="hljs-string">"www.google.com"</span>);

<span class="hljs-comment">// update to existing element in HTML</span>
<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".links"</span>).prepend(ele);
<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".links"</span>).append(ele);
<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".links"</span>).befor(ele);
<span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".links"</span>).after(ele);

<span class="hljs-comment">// Simalar to below anchor tag</span>
<span class="hljs-comment">// &lt;a href="www.google.com"&gt;Click Me&lt;/a&gt;</span>
</code></pre>
<p>In the above example, we created an anchor tag in JavaScript and added attributes and a classname to that anchor tag. We have four methods in the above example to update the created element in the HTML.</p>
<ul>
<li><p>prepend(): inserts the data at the top of its first child element.</p>
</li>
<li><p>append(): inserts the data or content inside an element at the last index.</p>
</li>
<li><p>before(): inserts the data before the selected element.</p>
</li>
<li><p>after(): puts the element after the specified element. Or you can say that it inserts data outside an element (making the content its sibling) in the set of matched elements.</p>
</li>
</ul>
<h3 id="heading-how-to-delete-elements">How to Delete Elements</h3>
<p>We know how to create elements in JavaScript and push them to the HTML. But what if we want to delete existing elements in the HTML? It's easy – we just need to use the <code>remove()</code> method on that element.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"p"</span>);

<span class="hljs-comment">// This will remove ele when clicked on</span>
ele.addEventListner(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    ele.remove();
})
</code></pre>
<h2 id="heading-how-to-manipulate-css-from-javascript">How to Manipulate CSS from JavaScript</h2>
<p>We know how to manipulate HTML from JavaScript. Now we will learn how to manipulate CSS from JavaScript. This can help you change the styling of your web pages dynamically.</p>
<p>For example, if you click on an element, its background color should change. This is possible by manipulating CSS from JavaScript.</p>
<p><strong>Here's some example syntax:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"desired element"</span>);

ele.style.propertyName = value;

<span class="hljs-comment">// E.g -</span>
ele.style.color = red;
</code></pre>
<p>When changing CSS properties using JavaScript, you need to make sure whenever there is a <code>-</code> in the CSS, you capitalize the next letter. For example, in CSS you would write <code>background-color</code>, but in JavaScript, <code>backgroundColor</code> (with a capital C).</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"div"</span>);
ele.style.backgroundColor = <span class="hljs-string">"red"</span>;
</code></pre>
<p>Now suppose you already wrote CSS for your project and you wanted to add classes using JavaScript. We can do that using <code>classList</code> in JavaScript.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".link"</span>);
ele.classList.add(<span class="hljs-string">"bg-red"</span>); <span class="hljs-comment">// add class bg-red to existing class list</span>
ele.classList.remove(<span class="hljs-string">"pb-4"</span>);<span class="hljs-comment">// remove class bg-red from existing class list</span>
ele.classList.toggle(<span class="hljs-string">"bg-green"</span>); <span class="hljs-comment">// toggle class bg-red to existing class list which means if it already exists then it will be removed, if it doesn't exist it will be added.</span>
</code></pre>
<p>When we use classList it adds, removes, or toggles classes directly to the element. It's like updating with existing classes.</p>
<p>Unlike element.className it removes all existing classes and adds the given class.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".link"</span>);
ele.classList.add(<span class="hljs-string">"bg-red"</span>); <span class="hljs-comment">// add class bg-red to existing class list</span>
ele.classList.remove(<span class="hljs-string">"pb-4"</span>);<span class="hljs-comment">// remove class bg-red from existing class list</span>

ele.className = <span class="hljs-string">"p-10"</span>; <span class="hljs-comment">// Now this will remove all existing classes and add only "p-10 class to element."</span>
</code></pre>
<h2 id="heading-how-to-use-event-handlers">How to Use Event Handlers</h2>
<p>The change in the state of an object is known as an <strong>Event</strong>. The process of reacting to the events is called <strong>Event Handling</strong>.</p>
<p>Events happen when a user does something like click, hover over an element, press a key, and so on. So when an event happens and you want to do a certain thing or manipulate anything, you use event handlers to trigger that event.</p>
<p>We use event handlers to execute certain code when that particular event happens. There are multiple event handlers in JavaScript (here's a quick <a target="_blank" href="https://way2tutorial.com/html/html5_events_handler_list.php">list of them</a>), but you use the same process to add event handlers to any element.</p>
<p><strong>Here's the syntax:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"a"</span>);

ele.addEventListner(<span class="hljs-string">"event"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-comment">// callback function</span>
});
</code></pre>
<p>Some events you can use:</p>
<ul>
<li><p>click</p>
</li>
<li><p>mouseover</p>
</li>
<li><p>mouseout</p>
</li>
<li><p>keypress</p>
</li>
<li><p>keydown</p>
</li>
</ul>
<p><strong>And here's an example of using the "click" event:</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"a"</span>);

ele.addEventListner(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    ele.style.backgroundColor = <span class="hljs-string">"pink"</span>;
});
</code></pre>
<h2 id="heading-event-propagation-bubbling-and-capturing">Event Propagation: Bubbling and Capturing</h2>
<p>Event Propagation determines in which order the elements receive the event(s). There are two ways to handle this event propagation order in the DOM: Event Bubbling and Event Capturing.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/Frame-71-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-what-is-event-bubbling">What is Event Bubbling?</h3>
<p>When an event happens on a component, it first runs the event handler on it, then on its parent component, then all the way up on the other ancestors’ components.</p>
<p>By default, all event handlers move through this order from center component event to outermost component event.</p>
<h3 id="heading-what-is-event-capturing">What is Event Capturing?</h3>
<p>This is the opposite of bubbling. The event handler acts first on its parent component and then on the component where it was actually meant to fire.</p>
<p>In short, this means that the event is first captured by the outermost element and propagated to the inner elements. It is also called trickle down.</p>
<p><strong>Let's try the below example:</strong></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Example<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
        <span class="hljs-selector-tag">nav</span>{
            <span class="hljs-attribute">display</span>: flex;
            <span class="hljs-attribute">justify-content</span>: center;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span>;
        }

        <span class="hljs-selector-tag">nav</span> <span class="hljs-selector-tag">li</span>{
            <span class="hljs-attribute">list-style</span>: none;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span>;
        }

        <span class="hljs-selector-tag">nav</span> <span class="hljs-selector-tag">li</span> <span class="hljs-selector-tag">a</span>{
            <span class="hljs-attribute">text-decoration</span>: none;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-keyword">const</span> navbar = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"nav"</span>);
        navbar.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            navbar.style.backgroundColor=<span class="hljs-string">"green"</span>
        });

        <span class="hljs-keyword">const</span> anchor = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"a"</span>);
        anchor.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            anchor.style.backgroundColor=<span class="hljs-string">"pink"</span>;
        })
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>This code gives us the following:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/Screenshot-2022-09-26-142920.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now study above example carefully. I have added an event listener to the <code>nav</code> tag and to the <code>anchor</code> tag. When you click on nav, the background color changes to green. When you click on the anchor tag, the background color changes to pink.</p>
<p>But when you click on the anchor tag, the background color of anchor as well as nav changes. This is because of <strong>event bubbling.</strong></p>
<p><strong>This is what happens when you only click on the nav element:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/Frame-72--1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong><em>This is what happens when you only click on the nav element.</em></strong></p>
<p><strong>This is what happens when you only click on the anchor element:</strong></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/Frame-73--1-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><strong><em>This is what happens when you only click on the anchor element</em></strong></p>
<p>To stop event propagation, we can use <code>stoppropagation()</code> on the event listener because of which the event propagation is happing. It will prevent the nav element event listener from getting activated in the above example.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Example<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
        <span class="hljs-selector-tag">nav</span>{
            <span class="hljs-attribute">display</span>: flex;
            <span class="hljs-attribute">justify-content</span>: center;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span>;
        }

        <span class="hljs-selector-tag">nav</span> <span class="hljs-selector-tag">li</span>{
            <span class="hljs-attribute">list-style</span>: none;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span>;
        }

        <span class="hljs-selector-tag">nav</span> <span class="hljs-selector-tag">li</span> <span class="hljs-selector-tag">a</span>{
            <span class="hljs-attribute">text-decoration</span>: none;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">20px</span>;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">nav</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">nav</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
        <span class="hljs-keyword">const</span> navbar = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"nav"</span>);
        navbar.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
            navbar.style.backgroundColor=<span class="hljs-string">"green"</span>
        });

        <span class="hljs-keyword">const</span> anchor = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"a"</span>);
        anchor.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>)</span>{
            e.stopPropagation();
            anchor.style.backgroundColor=<span class="hljs-string">"pink"</span>;
        })
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h2 id="heading-how-to-traverse-the-dom">How to Traverse the DOM</h2>
<p>"A good JavaScript developer needs to know how to traverse the DOM— it’s <strong>the act of selecting an element from another element.</strong> " – <a target="_blank" href="https://zellwk.com/blog/dom-traversals/">Zell Liew</a></p>
<p>Now we are going to see why traversing the DOM is better than using the <code>document.querySelector()</code> method, and how to traverse like a pro.</p>
<p>There are 3 ways to traverse the DOM:</p>
<ul>
<li><p>Upward</p>
</li>
<li><p>Downward</p>
</li>
<li><p>Sideways</p>
</li>
</ul>
<h3 id="heading-how-to-traverse-the-dom-upward">How to traverse the DOM upward</h3>
<p>There are two methods which help you traverse the DOM upward:</p>
<ul>
<li><p>parentElement</p>
</li>
<li><p>closest</p>
</li>
</ul>
<p><code>parentElement</code> is a property that selects the parent element, like this:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"a"</span>);
<span class="hljs-built_in">console</span>.log(ele.parentElement); <span class="hljs-comment">// &lt;div&gt;</span>
</code></pre>
<p>The parentElement is great for selecting one level upwards. But <code>closest</code> lets you find an element that can be multiple levels above the current element. <code>closest</code> lets you select the closest ancestor element that matches a selector.</p>
<p>Here's an example of using <code>closest</code>:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">article</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"target"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"heading"</span>&gt;</span>This is the main heading<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"outer-div"</span>&gt;</span>
        This is the outer div
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"inner-div"</span>&gt;</span>This is the inner div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> innerDiv = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"#inner-div"</span>);
<span class="hljs-built_in">console</span>.log(innerDiv.closest(<span class="hljs-string">"#target"</span>)); <span class="hljs-comment">// article#target</span>
</code></pre>
<p>In above code we are trying to get closest element to <code>.heading</code> which has a class of <code>.demo</code>.</p>
<h3 id="heading-how-to-traverse-the-dom-downward">How to traverse the DOM downward</h3>
<p>We can traverse downward using the <code>children</code> method on a selector. With children you can select direct child of selected element.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Link-1<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Link-2<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Link-3<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Link-4<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"div"</span>);
<span class="hljs-keyword">const</span> child = ele.children;

<span class="hljs-built_in">console</span>.log(child); <span class="hljs-comment">// gives HTMLCollection</span>
<span class="hljs-comment">// 4 element inside div</span>
</code></pre>
<h3 id="heading-how-to-traverse-the-dom-sideways">How to traverse the DOM sideways</h3>
<p>It's very interesting to traverse the DOM sideways. There are mainly two methods we can use:</p>
<ul>
<li><p>previousElementSibling</p>
</li>
<li><p>nextElementSibling</p>
</li>
</ul>
<p>With the help of the <code>previousElementSibling</code> method, we can select previous elements in the HTML like this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Link-1<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Heading<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"h1"</span>);
<span class="hljs-built_in">console</span>.log(ele.previousElementSibling); <span class="hljs-comment">// &lt;a href="#"&gt;Link-1&lt;/a&gt;</span>
</code></pre>
<p>With the help of <code>nextElementSibling</code>, we can select the next element in the HTML like this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span>&gt;</span>Link-1<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Heading<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> ele = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"a"</span>);
<span class="hljs-built_in">console</span>.log(ele.nextElementSibling); <span class="hljs-comment">// &lt;h1&gt;Heading&lt;/h1&gt;</span>
</code></pre>
<h2 id="heading-wrapping-up"><strong>Wrapping Up</strong></h2>
<p>I hope you now understand how the DOM works in JavaScript. Thank you for reading!</p>
<p>You can follow me on:</p>
<ul>
<li><p><a target="_blank" href="https://twitter.com/Kedar__98">Twitter</a></p>
</li>
<li><p><a target="_blank" href="https://www.linkedin.com/in/kedar-makode-9833321ab/?originalSubdomain=in">LinkedIn</a></p>
</li>
<li><p><a target="_blank" href="https://www.instagram.com/kedar_98/">Instagram</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How the JavaScript DOM Works – A Practical Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ If you were listening to music on an app and you wanted to pause or skip a song, you'd have to do that through the app. This process is similar to how the Document Object Model or DOM works. Here, the music app represents the DOM because it serves as... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-javascript-dom-a-practical-tutorial/</link>
                <guid isPermaLink="false">66c5a343215f782a032b1cb9</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ophy Boamah ]]>
                </dc:creator>
                <pubDate>Mon, 12 Sep 2022 20:19:15 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/DOMpract-2-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you were listening to music on an app and you wanted to pause or skip a song, you'd have to do that through the app.</p>
<p>This process is similar to how the Document Object Model or DOM works. Here, the music app represents the DOM because it serves as a medium to make changes to the music.</p>
<p>In this tutorial, you'll learn what the DOM is and how it works in a practical way.</p>
<h2 id="heading-what-is-the-dom">What is the DOM?</h2>
<p>The DOM is a Web API that allows developers to use programming logic to make changes to their HTML code. It's a reliable way to make changes that turn static websites into dynamic ones. </p>
<p>It's an important topic in web development because the DOM serves as the initial use of JavaScript in the browser. </p>
<p>HTML code isn’t considered part of the DOM until its parsed by the browser. To see what happens to your HTML code when this parsing happens, copy your code from the <strong><code>&lt;body&gt;</code></strong> tag and paste it <a target="_blank" href="https://software.hixie.ch/utilities/js/live-dom-viewer/">here</a> (within the box with the title 'Markup to test' after the three dots).</p>
<h2 id="heading-what-are-we-building">What are we building?</h2>
<p>In this article, we’re going to learn the most important and often used parts of the DOM by building this simple project:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/domProject-1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Check it out on CodePen <a target="_blank" href="https://codepen.io/ophyboamah/pen/bGMdbve">here</a>.</p>
<h2 id="heading-project-functionality">Project Functionality</h2>
<p>As you can see in the project demo above, these are the functionalities we’ll implement:</p>
<ol>
<li><strong>Dynamic color change</strong>: When a color is clicked, the color of the car image, addToCart button, and tag all change to match the selected color.</li>
<li><strong>Button switch</strong>: Clicking on the addToCart button reveals the success button and vice versa.</li>
</ol>
<h2 id="heading-prerequisites">Prerequisites</h2>
<ul>
<li>basic knowledge of HTML and CSS.</li>
<li>basic knowledge of JavaScript</li>
<li>an IDE (text editor)</li>
<li>a web browser</li>
</ul>
<p><strong>NB:</strong> Because the goal of the article is to learn about JavaScript and the DOM, we won't place a lot of emphasis on the HTML and CSS code. We'll just go through it quickly first so you can set up the app. Then we'll dive into learning about the DOM.</p>
<h2 id="heading-html-code">HTML code:</h2>
<p>In our <code>index.html</code> file, we'll create the basic structure of the project which includes linking our CSS file, Font Awesome, and Google Fonts – all within our <code>&lt;head&gt;</code> tag. Within our <code>&lt;body&gt;</code> tag, we'll create our product card and link our JavaScript tag at the end of the <code>&lt;body&gt;</code> tag.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span>
      <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>
      <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css"</span>
      <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A=="</span>
      <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>
      <span class="hljs-attr">referrerpolicy</span>=<span class="hljs-string">"no-referrer"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preconnect"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.gstatic.com"</span> <span class="hljs-attr">crossorigin</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span>
      <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&amp;display=swap"</span>
      <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Practicalized DOM<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-card"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-image"</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- &lt;img src="./img/gray-benz.jpg" alt="cars" /&gt; --&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-description"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"tag"</span>&gt;</span>CAR<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-title"</span>&gt;</span>Mercedez Benz c300 2022<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-details"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mileage"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"font-size: 1em; color: black"</span>
              &gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-car"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>
            &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            Mileage: 4,000 miles
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fuel"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"font-size: 1em; color: black"</span>
              &gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-gas-pump"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>
            &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            Fuel: 25mpg
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"safety"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"font-size: 1em; color: black"</span>
              &gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-shield"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>
            &gt;</span>Safety:
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"stars"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pick a color:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"colors-price"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"colors"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"red"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"gray"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"black"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pricing"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"new-price"</span>&gt;</span>$134,450<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h4</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"old-price"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">s</span>&gt;</span>$140,500<span class="hljs-tag">&lt;/<span class="hljs-name">s</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"button"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"font-size: 1em; color: white"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-cart-shopping"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button-text"</span>&gt;</span>Add to Cart<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"feedback"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"white-button"</span>
            &gt;</span>🥳 Woohoo, You're about to own a benz 🎊<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>
          &gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"app.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h2 id="heading-css-code">CSS code:</h2>
<p>In our <code>style.css</code> file, we'll first of all set our general styles like this:</p>
<pre><code class="lang-css">* {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Poppins"</span>, sans-serif;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">overflow-y</span>: hidden;
  <span class="hljs-attribute">background-color</span>: antiquewhite;
}
</code></pre>
<p>Next, we'll style our product, starting with the tag, image, description and details.</p>
<pre><code class="lang-css"><span class="hljs-comment">/* product tag */</span>
<span class="hljs-selector-class">.tag</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">0.9rem</span>;
  <span class="hljs-attribute">background-color</span>: black;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">4rem</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
}

<span class="hljs-comment">/* product*/</span>
<span class="hljs-selector-class">.product-title</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">700</span>;
}

<span class="hljs-selector-class">.product-card</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-comment">/* align-items: center; */</span>
  <span class="hljs-attribute">grid-template-rows</span>: <span class="hljs-number">55%</span> <span class="hljs-number">45%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">80%</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">30%</span>;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">10px</span> <span class="hljs-number">10px</span> <span class="hljs-number">25px</span> <span class="hljs-number">0px</span> <span class="hljs-number">#3c3c3c</span>;
}

<span class="hljs-selector-class">.product-image</span> {
  <span class="hljs-comment">/* border: 2px solid black; */</span>
  <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(<span class="hljs-string">"./img/black-benz.jpg"</span>);
  <span class="hljs-attribute">background-position</span>: center;
  <span class="hljs-attribute">background-repeat</span>: no-repeat;
  <span class="hljs-attribute">background-size</span>: cover;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">40px</span> <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">28rem</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">66%</span>;
}

<span class="hljs-selector-class">.product-description</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#62c256</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">padding-left</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">margin-top</span>: -<span class="hljs-number">67px</span>;
}

<span class="hljs-selector-class">.product-details</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">margin-top</span>: -<span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.product-image</span> <span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">28rem</span>;
}

<span class="hljs-selector-class">.stars</span> {
  <span class="hljs-attribute">color</span>: yellow;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1em</span>;
}
</code></pre>
<p>Then, we'll style our colors: their prices, colors as a group, and individual colors.</p>
<pre><code class="lang-css"><span class="hljs-comment">/* colors */</span>
<span class="hljs-selector-class">.colors-price</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70%</span>;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">margin-top</span>: -<span class="hljs-number">15px</span>;
}

<span class="hljs-selector-class">.colors</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">6rem</span>;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-class">.red</span> {
  <span class="hljs-attribute">background</span>: red;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>;
}

<span class="hljs-selector-class">.gray</span> {
  <span class="hljs-attribute">background</span>: gray;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>;
}

<span class="hljs-selector-class">.black</span> {
  <span class="hljs-attribute">background</span>: black;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>;
}

<span class="hljs-selector-class">.pricing</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">12rem</span>;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">align-items</span>: center;
}

<span class="hljs-selector-class">.old-price</span> {
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">100</span>;
}
</code></pre>
<p>Finally, we'll style our buttons with this code:</p>
<pre><code class="lang-css"><span class="hljs-comment">/* buttons */</span>
<span class="hljs-selector-tag">button</span> {
  <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-id">#button</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#000</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-tag">button</span> <span class="hljs-selector-tag">white-button</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
}

<span class="hljs-selector-class">.button-text</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">margin-left</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-class">.feedback</span> {
  <span class="hljs-attribute">display</span>: none;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}
</code></pre>
<h2 id="heading-dom-implementation">DOM Implementation</h2>
<p>Everything in the DOM falls into one of these two categories: selecting elements and manipulating elements. After creating our HTML and CSS files, we head into our <code>app.js</code> file to implement the following:</p>
<ol>
<li><strong>Select</strong>: We reference all elements we want to make dynamic from our HTML code and assign them variables in our JavaScript file.</li>
<li><strong>Manipulate</strong>: Once we have selected and linked the variables, we create the various functions responsible for the manipulations and then link to the variables. </li>
</ol>
<h2 id="heading-how-to-select-elements-in-the-dom">How to Select Elements in the DOM</h2>
<p>To get access to the HTML elements that you want to manipulate, you need to make the JavaScript aware that such elements exist. This is what is generally referred to as "selecting" elements – basically linking them. </p>
<p>In the DOM, there’s no one way to locate and reference an element for manipulation. Instead, it’ll depend on the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors">selector</a> you've used in the element's tag. </p>
<p>You do this by assigning the element to a variable. It takes the following format. Keep in mind that <em>all DOM selectors are preceded by the document object and a dot</em>:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> example = <span class="hljs-built_in">document</span>.[DOMselector]
</code></pre>
<p>In our JavaScript file, we have to select all the elements that we want to manipulate such as the button, the colors, the image card, and the tag. </p>
<p>We’re going to use as many of the DOM selectors as possible, so let's learn more about them.</p>
<h3 id="heading-how-to-use-queryselector">How to use <code>querySelector</code></h3>
<p><code>querySelector</code> is a method which accepts the exact CSS selector in a string and returns one element. You can use it to select the red and black colors as well as the image card, using their class names.</p>
<p>If you wanted to use this approach to select and return more than one element, you can use <strong><code>QuerySelectorAll</code></strong> instead.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> redColor = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".red"</span>);
</code></pre>
<p>The code above links the span with class "red" <code>&lt;span class="red"&gt;&lt;/span&gt;</code> from our HTML code to the variable redColor in our JavaScript.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> blackColor = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".black"</span>);
</code></pre>
<p>The code above links the span with class "black" <code>&lt;span class="black"&gt;&lt;/span&gt;</code> from our HTML code to the variable blackColor in our JavaScript.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> imageCard = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".product-image"</span>);
</code></pre>
<p>The code above links the div with class "product-image" <code>&lt;div class="product-image"&gt;</code> from our HTML code to the variable imageCard in our JavaScript.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> feedbackBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".feedback"</span>);
</code></pre>
<p>The code above links the button with class "feedback" <code>&lt;button class="feedback"&gt;</code> from our HTML code to the variable feedbackBtn in our JavaScript. </p>
<h3 id="heading-how-to-use-getelementsbyclassname">How to use <code>getElementsByClassName</code></h3>
<p>You can use this selector to select the gray color. It's very similar to the <code>querySelector</code>. The only difference is that this method accepts just the name of the class, without the preceding dot (.)</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> grayColor = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"gray"</span>);
</code></pre>
<p>The code above links the span with class "gray" <code>&lt;span class="gray"&gt;&lt;/span&gt;</code> from our HTML code to the variable grayColor in our JavaScript.</p>
<h3 id="heading-how-to-use-getelementbyid">How to use <code>getElementById</code></h3>
<p>You can use this selector to select the cart button. It's very similar to the <code>getElementsByClassName</code>. The only difference is that because we use the ID to show uniqueness, it's used on only one element. This method reads getElement, <em>without an s</em>. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cartButton = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"button"</span>);
</code></pre>
<p>The code above links the button with id "button" <code>&lt;button id="button"&gt;</code> from our HTML code to the variable cartButton in our JavaScript. </p>
<h3 id="heading-how-to-use-getelementsbytagname">How to use <code>GetElementsByTagName</code></h3>
<p>Attributes are not the only ways to select an element. You can also use tag names. If you've used the tag you're targeting more than once, then it will return a list of elements. Use indexing to select the right one.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> itemTag = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"h3"</span>)[<span class="hljs-number">0</span>];
</code></pre>
<p>The code above links the h3 that contains our product tag <code>&lt;h3 class="tag"&gt;</code> from our HTML code to the variable itemTag in our JavaScript. </p>
<p>Of all these, the querySelector and querySelectorAll are probably the most popular because of how general and less restricting they are.</p>
<h2 id="heading-how-to-manipulate-elements-in-the-dom">How to Manipulate Elements in the DOM</h2>
<p>Manipulation is the main purpose of the DOM. It's everything that happens after you reference and select the element(s) you want to work with. This leads to a change in the state of the element, from static to dynamic. </p>
<p>Two concepts that you need to know to understand DOM manipulation are <strong>events</strong> and <strong>handlers</strong>. </p>
<h3 id="heading-what-are-events">What are Events?</h3>
<p>Let's use the same music analogy from earlier. On the music app, you have to perform an action [click or swipe] before the functionalities kick in. </p>
<p>In the DOM, this action is known as an event. There are events such as click, scroll, mouseover, change, and more. </p>
<p>In the DOM, responses are tied to each event. This means that there should be a lookout for the event in order to give a response. This is known as an <strong>event listener</strong>. Event listeners usually come in the form of an <code>addEventListener</code> method which takes two arguments(event, event handler).</p>
<h4 id="heading-anatomy-of-an-event">Anatomy of an Event</h4>
<p>DOM events normally contain an element, its event listener, and a function.</p>
<pre><code>element.[eventListenerMethod(event, eventHandler)
</code></pre><h3 id="heading-what-are-event-handlers">What are Event Handlers?</h3>
<p>Event handlers are the responses that are triggered when our event listener methods read an event. Without event handlers, there would be no way to alert our code that an event has occurred. </p>
<p>All the modifications that happen within the DOM such as styling, appending, removing, and so on rely on event handlers. They are the functions found in the second argument of an <strong>addEventListener</strong> method. They are always alert to run as soon as the event (first argument) happens.</p>
<pre><code class="lang-javascript">redColor.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  cartButton.style.backgroundColor = <span class="hljs-string">"red"</span>;
  itemTag.style.backgroundColor = <span class="hljs-string">"red"</span>;
  imageCard.style.backgroundImage = <span class="hljs-string">'url("./img/red-benz.webp")'</span>;
});
</code></pre>
<p>In the code above, the function after the 'click' event, is the event handler. This means that everything within that function will be implemented as soon as the red color is clicked.</p>
<h2 id="heading-how-to-implement-events-and-event-handlers">How to Implement Events and Event Handlers</h2>
<p>In this project, we’re going to use events and event handlers for about 5 implementations. We'll go through each one now.</p>
<p>First, we'll use them to <strong>make the red color functional</strong>. Once a user clicks the red color, the cart button and item tag are assigned styles in the form of a red background color. The image card also gets assigned a red background image. </p>
<p>We do this by taking the variable <code>redColor</code> and adding an event listener of 'click'. This means we want our code to be alerted when the red color is clicked. In return, the event handler <code>function</code> is in place to run immediately. </p>
<pre><code class="lang-javascript">redColor.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  cartButton.style.backgroundColor = <span class="hljs-string">"red"</span>;
  itemTag.style.backgroundColor = <span class="hljs-string">"red"</span>;
  imageCard.style.backgroundImage = <span class="hljs-string">'url("./img/red-benz.webp")'</span>;
});
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/redColor-1.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Red color preview</em></p>
<p>Then we'll <strong>make the gray color functional</strong>. When a user clicks the gray color, the cart button and item tag are assigned styles in the form of a gray background color. The image card is also assigned a gray background image. </p>
<p>We do this by taking the variable <code>grayColor</code> and adding an event listener of 'click'. This means we want our code to be alerted when the gray color is clicked. In return, the event handler <code>function</code> is in place to run immediately. </p>
<pre><code class="lang-javascript">grayColor[<span class="hljs-number">0</span>].addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  cartButton.style.backgroundColor = <span class="hljs-string">"gray"</span>;
  itemTag.style.backgroundColor = <span class="hljs-string">"gray"</span>;
  imageCard.style.backgroundImage = <span class="hljs-string">'url("./img/gray-benz.jpg")'</span>;
});
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/grayColor-1.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Gray color preview</em></p>
<p>Next we'll make the <strong>black color functional</strong>. When the user clicks the black color, the cart button and item tag are assigned styles in the form of a black background color. The image card is also assigned a black background image. </p>
<p>We do this by taking the variable <code>blackColor</code> and adding an event listener of 'click'. This means we want our code to be alerted when the black color is clicked. In return, the event handler <code>function</code> is in place to run immediately. </p>
<pre><code class="lang-javascript">blackColor.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  cartButton.style.backgroundColor = <span class="hljs-string">"black"</span>;
  itemTag.style.backgroundColor = <span class="hljs-string">"black"</span>;
  imageCard.style.backgroundImage = <span class="hljs-string">'url("./img/black-benz.jpg")'</span>;
});
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/blackColor-1.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Black color preview</em></p>
<p>We've looked at one approach to event handlers, which is creating the function within the addEventListener method. </p>
<p>Another approach is to create a function before passing the name of the function as an argument in the addEventListener method. </p>
<h3 id="heading-how-to-implement-the-cart-button">How to Implement the Cart Button</h3>
<p>We start by creating a function named cart. The cart function hides the cart button and shows the feedback button. The function name cart is then passed to the event listener method as the second argument.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> cart = <span class="hljs-function">() =&gt;</span> {
  cartButton.style.display = <span class="hljs-string">"none"</span>;
  feedbackBtn.style.display = <span class="hljs-string">"block"</span>;
};
cartButton.addEventListener(<span class="hljs-string">"click"</span>, cart);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/cartButton.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Cart button preview</em></p>
<h3 id="heading-how-to-implement-the-feedback-button">How to Implement the Feedback Button</h3>
<p>We first create a function named feedback. The feedback function hides the feedback button and shows the cart button. The function name feedback is then passed to the event listener method as the second argument. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> feedback = <span class="hljs-function">() =&gt;</span> {
  cartButton.style.display = <span class="hljs-string">"block"</span>;
  feedbackBtn.style.display = <span class="hljs-string">"none"</span>;
};
feedbackBtn.addEventListener(<span class="hljs-string">"click"</span>, feedback);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/feedbackButton.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Feedback button preview</em></p>
<h2 id="heading-full-project-code">Full Project Code</h2>
<p>This is the project we’ve built together in this article:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/domProject-2.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here's the full HTML code:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span>
      <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>
      <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css"</span>
      <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha512-1sCRPdkRXhBV2PBLUdRb4tMg1w2YPf37qatUFeS7zlBy7jJI8Lf4VHwWfZZfpXtYSLy85pkm9GaYVYMfw5BC1A=="</span>
      <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>
      <span class="hljs-attr">referrerpolicy</span>=<span class="hljs-string">"no-referrer"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preconnect"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.gstatic.com"</span> <span class="hljs-attr">crossorigin</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span>
      <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&amp;display=swap"</span>
      <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>
    /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Practicalized DOM<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-card"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-image"</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- &lt;img src="./img/gray-benz.jpg" alt="cars" /&gt; --&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-description"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"tag"</span>&gt;</span>CAR<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-title"</span>&gt;</span>Mercedez Benz c300 2022<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"product-details"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mileage"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"font-size: 1em; color: black"</span>
              &gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-car"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>
            &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            Mileage: 4,000 miles
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fuel"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"font-size: 1em; color: black"</span>
              &gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-gas-pump"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>
            &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            Fuel: 25mpg
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"safety"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"font-size: 1em; color: black"</span>
              &gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-shield"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>
            &gt;</span>Safety:
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"stars"</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-star"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Pick a color:<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"colors-price"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"colors"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"red"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"gray"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"black"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pricing"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"new-price"</span>&gt;</span>$134,450<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h4</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"old-price"</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">s</span>&gt;</span>$140,500<span class="hljs-tag">&lt;/<span class="hljs-name">s</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"button"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">style</span>=<span class="hljs-string">"font-size: 1em; color: white"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">i</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"fa-solid fa-cart-shopping"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">i</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"button-text"</span>&gt;</span>Add to Cart<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"feedback"</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"white-button"</span>
            &gt;</span>🥳 Woohoo, You're about to own a benz 🎊<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>
          &gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"app.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Here's the CSS:</p>
<pre><code class="lang-css">* {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">"Poppins"</span>, sans-serif;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">overflow-y</span>: hidden;
  <span class="hljs-attribute">background-color</span>: antiquewhite;
}

<span class="hljs-comment">/* product tag */</span>
<span class="hljs-selector-class">.tag</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">0.9rem</span>;
  <span class="hljs-attribute">background-color</span>: black;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">4rem</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
}

<span class="hljs-comment">/* product*/</span>
<span class="hljs-selector-class">.product-title</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2rem</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">700</span>;
}

<span class="hljs-selector-class">.product-card</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">display</span>: grid;
  <span class="hljs-comment">/* align-items: center; */</span>
  <span class="hljs-attribute">grid-template-rows</span>: <span class="hljs-number">55%</span> <span class="hljs-number">45%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">80%</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">30%</span>;
  <span class="hljs-attribute">box-shadow</span>: <span class="hljs-number">10px</span> <span class="hljs-number">10px</span> <span class="hljs-number">25px</span> <span class="hljs-number">0px</span> <span class="hljs-number">#3c3c3c</span>;
}

<span class="hljs-selector-class">.product-image</span> {
  <span class="hljs-comment">/* border: 2px solid black; */</span>
  <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(<span class="hljs-string">"./img/black-benz.jpg"</span>);
  <span class="hljs-attribute">background-position</span>: center;
  <span class="hljs-attribute">background-repeat</span>: no-repeat;
  <span class="hljs-attribute">background-size</span>: cover;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">40px</span> <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">28rem</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">66%</span>;
}

<span class="hljs-selector-class">.product-description</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#62c256</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">padding-left</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">margin-top</span>: -<span class="hljs-number">67px</span>;
}

<span class="hljs-selector-class">.product-details</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">margin-top</span>: -<span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.product-image</span> <span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">28rem</span>;
}

<span class="hljs-selector-class">.stars</span> {
  <span class="hljs-attribute">color</span>: yellow;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1em</span>;
}

<span class="hljs-comment">/* colors */</span>
<span class="hljs-selector-class">.colors-price</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">70%</span>;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">margin-top</span>: -<span class="hljs-number">15px</span>;
}

<span class="hljs-selector-class">.colors</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">6rem</span>;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-class">.red</span> {
  <span class="hljs-attribute">background</span>: red;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>;
}

<span class="hljs-selector-class">.gray</span> {
  <span class="hljs-attribute">background</span>: gray;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>;
}

<span class="hljs-selector-class">.black</span> {
  <span class="hljs-attribute">background</span>: black;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50%</span>;
}

<span class="hljs-selector-class">.pricing</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">12rem</span>;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">align-items</span>: center;
}

<span class="hljs-selector-class">.old-price</span> {
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">100</span>;
}

<span class="hljs-comment">/* buttons */</span>
<span class="hljs-selector-tag">button</span> {
  <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-id">#button</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#000</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-tag">button</span> <span class="hljs-selector-tag">white-button</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#fff</span>;
}

<span class="hljs-selector-class">.button-text</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
  <span class="hljs-attribute">margin-left</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-class">.feedback</span> {
  <span class="hljs-attribute">display</span>: none;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}
</code></pre>
<p>Here's the JavaScript code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// 1. Change color of car and addToCart button color when a color is selected</span>
<span class="hljs-comment">// - Selecting Elements</span>
<span class="hljs-keyword">const</span> redColor = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".red"</span>);
<span class="hljs-keyword">const</span> grayColor = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"gray"</span>);
<span class="hljs-keyword">const</span> blackColor = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".black"</span>);
<span class="hljs-keyword">const</span> cartButton = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"button"</span>);
<span class="hljs-keyword">const</span> itemTag = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"h3"</span>)[<span class="hljs-number">0</span>];
<span class="hljs-keyword">const</span> imageCard = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".product-image"</span>);
<span class="hljs-keyword">const</span> feedbackBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".feedback"</span>);

<span class="hljs-comment">// Modifying Elements</span>
<span class="hljs-comment">// - Add Event Listeners</span>
<span class="hljs-comment">// - Red Color</span>
redColor.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  cartButton.style.backgroundColor = <span class="hljs-string">"red"</span>;
  itemTag.style.backgroundColor = <span class="hljs-string">"red"</span>;
  imageCard.style.backgroundImage = <span class="hljs-string">'url("./img/red-benz.webp")'</span>;
});

<span class="hljs-comment">// - Gray Color</span>
grayColor[<span class="hljs-number">0</span>].addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  cartButton.style.backgroundColor = <span class="hljs-string">"gray"</span>;
  itemTag.style.backgroundColor = <span class="hljs-string">"gray"</span>;
  imageCard.style.backgroundImage = <span class="hljs-string">'url("./img/gray-benz.jpg")'</span>;
});

<span class="hljs-comment">// - Black Color</span>
blackColor.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  cartButton.style.backgroundColor = <span class="hljs-string">"black"</span>;
  itemTag.style.backgroundColor = <span class="hljs-string">"black"</span>;
  imageCard.style.backgroundImage = <span class="hljs-string">'url("./img/black-benz.jpg")'</span>;
});

<span class="hljs-comment">// Button Click Implementation</span>
<span class="hljs-comment">// - Cart Button</span>
<span class="hljs-keyword">const</span> cart = <span class="hljs-function">() =&gt;</span> {
  cartButton.style.display = <span class="hljs-string">"none"</span>;
  feedbackBtn.style.display = <span class="hljs-string">"block"</span>;
};
cartButton.addEventListener(<span class="hljs-string">"click"</span>, cart);

<span class="hljs-comment">// - Feedback Button</span>
<span class="hljs-keyword">const</span> feedback = <span class="hljs-function">() =&gt;</span> {
  cartButton.style.display = <span class="hljs-string">"block"</span>;
  feedbackBtn.style.display = <span class="hljs-string">"none"</span>;
};
feedbackBtn.addEventListener(<span class="hljs-string">"click"</span>, feedback);
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>The DOM is an essential part of modern web development because it helps developers transform websites and web applications from static to dynamic. </p>
<p>As a beginner, it can be quite hard to wrap your head around the DOM and all that it entails. Taking time to build a few simple projects like this will help you reinforce the concepts. </p>
<p>Thanks for reading 👋🏾. I hope you found it helpful.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the DOM? The Document Object Model Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ Modern web pages are dynamic. This means we need a suitable and convenient way to modify and manipulate a web document's structure. This modification in an HTML document, for instance, usually takes the form of creating, adding, or removing elements ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-the-dom-explained-in-plain-english/</link>
                <guid isPermaLink="false">66d45e0e3dce891ac3a967da</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Damilola Oladele ]]>
                </dc:creator>
                <pubDate>Wed, 22 Jun 2022 17:54:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/06/DOM-cover-2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Modern web pages are dynamic. This means we need a suitable and convenient way to modify and manipulate a web document's structure.</p>
<p>This modification in an HTML document, for instance, usually takes the form of creating, adding, or removing elements in the document.</p>
<p>In this article, you'll learn what the <strong>Document Object Model (DOM)</strong> is, a bit about its history, and how you use it to manipulate web documents, especially HTML documents.</p>
<h2 id="heading-what-is-the-document-object-model-dom">What is the Document Object Model (DOM)?</h2>
<p>The DOM is a web interface, developed and released by the <strong>World Wide Web Consortium (</strong><a target="_blank" href="https://www.w3.org/"><strong>W3C</strong></a><strong>)</strong>. This organization was founded to establish standards for the World Wide Web.</p>
<p>The DOM is a web API that is language-neutral. This means that you can implement and adopt it in any programming language.</p>
<p>The DOM represents the structural pieces of a web document as objects that can be accessed and manipulated. In other words, the DOM allows you as a software developer to do the following:</p>
<ul>
<li><p>Create and build web documents.</p>
</li>
<li><p>Navigate the structure of web documents.</p>
</li>
<li><p>Add, modify, or delete elements and content within web documents.</p>
</li>
</ul>
<h2 id="heading-history-of-the-dom">History of the DOM</h2>
<p>The history of the DOM is relative to JavaScript and JScript as the first widely used scripting languages. These languages helped make web pages interactive.</p>
<p>Prior to the development of a standard DOM specification by the W3C, JavaScript and JScript had different ways of enabling access to manipulating HTML documents.</p>
<p>These limited methods and interfaces that let you manipulate HTML documents in this way became the <strong>DOM Level 0</strong>.</p>
<p>In 1998, the W3C completed its draft of the first standard DOM specification, which became the recommended standard for all browsers. This standard DOM specification became <strong>DOM Level 1</strong>. The DOM level 1 provided a comprehensive model for manipulating both HTML and XML documents.</p>
<p>In 2000, the W3C released <strong>DOM Level 2</strong>, which introduced methods such as <code>getElementById()</code>, as well as a standardized event model and support for XML namespaces and CSS.</p>
<p>The <strong>DOM Level 3</strong>, released in 2004, added support for XPath and keyboard event handling. And in late 2015, the latest DOM specification, <strong>DOM Level 4</strong>, became a published standard.</p>
<h2 id="heading-what-is-the-dom-tree">What is the DOM Tree?</h2>
<p>The structural representation created by the DOM is very much like a tree. It has several objects in it known as nodes.</p>
<p>The browser uses the DOM tree representation it builds from an HTML document to determine what to render on a web page. For example, a visual representation of a DOM tree will look like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/DOM-tree.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p><em>The DOM Tree</em></p>
<p>The HTML document of the above DOM tree looks like this:</p>
<pre><code class="lang-javascript">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;TITLE&lt;/title&gt;
    &lt;link rel="stylesheet" href="style.css"&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div&gt;
        &lt;h1&gt;HELLO WORLD&lt;/h1&gt;
    &lt;/div&gt;
    &lt;a href="link text"&gt;Document Object Model&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h3 id="heading-nodes-vs-elements-in-the-dom">Nodes vs Elements in the DOM</h3>
<p>Often, developers confuse nodes with elements. So we should distinguish between the two early in this article to avoid confusion.</p>
<p><strong>Nodes</strong> are all the components a web page document is made up of. In other words, a web page is collection of nodes.</p>
<p>An <strong>element</strong> is a type of node within a document. For instance, the DOM property <code>nodes.childNodes</code> when used on a parent node will return all the different nodes contained within that specified parent node.</p>
<p>In the example below, the childNodes property is used on the <code>&lt;body&gt;</code> element node of the HTML document given above:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-comment">//select the &lt;body&gt; element node with the DOM method querySelector</span>
<span class="hljs-keyword">const</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>) 
<span class="hljs-comment">//select the children nodes with the &lt;body&gt; element node with the DOM property node.childNodes</span>
<span class="hljs-keyword">const</span> childrenNodes = body.childNodes
<span class="hljs-comment">//console log the children nodes</span>
<span class="hljs-built_in">console</span>.log(childrenNodes)<span class="hljs-comment">//NodeList(5) [text, div, text, a, text]</span>
</code></pre>
<p>Notice that there are five items in the <code>nodeList</code>. This is because we have another type of node, the text nodes, different from the element nodes within the <code>&lt;body&gt;</code> element node.</p>
<p>To investigate this further, go through the following steps in your console:</p>
<ol>
<li><p>Click on the dropdown icon just before "nodeList".</p>
</li>
<li><p>Select the text node by clicking on the dropdown icon before "test".</p>
</li>
<li><p>Check for the textContent option within the list options in the dropdown.</p>
</li>
</ol>
<p>If you follow the above instructions, you will see that the test content of the first text node is "/n ". This is a text node indicating a new line after the <code>&lt;body&gt;</code> element node, the <code>&lt;div&gt;</code> element node, and the <code>&lt;a&gt;</code> element node.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--143--1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-relationships-between-nodes-in-the-dom-tree">Relationships Between Nodes in the DOM Tree</h3>
<p>The nodes in the DOM tree have a hierarchical relationship with each other in the DOM tree. They are defined by their position relative to each other in the DOM tree.</p>
<p>These are the node positions present in the DOM tree illustration above:</p>
<ul>
<li><p><strong>Root node</strong>: The root node is always at the apex of the DOM tree. In an HTML document, the root node is always the <code>&lt;html&gt;</code> element.</p>
</li>
<li><p><strong>Child node</strong>: A child node is a node embedded inside another node. In the illustration given above, the <code>&lt;head&gt;</code> and the <code>&lt;body&gt;</code> elements are the children of the <code>&lt;html&gt;</code> element.</p>
</li>
<li><p><strong>Descendant node</strong>: Any node positioned below another node in the hierarchical order is the descendant of the nodes positioned above it. For example, although the <code>&lt;h1&gt;</code> element is not the direct child of the <code>&lt;body&gt;</code> element, it is a descendant of the <code>&lt;body&gt;</code> and root <code>&lt;html&gt;</code> elements.</p>
</li>
<li><p><strong>Parent node</strong>: Any node which has another node inside it is a parent node. For example, the <code>&lt;body&gt;</code> element is the parent of the <code>&lt;div&gt;</code> and <code>&lt;a&gt;</code> elements in the above example. Note that only element type nodes can be a parent node.</p>
</li>
<li><p><strong>Sibling nodes</strong>: Nodes that are on the same level in hierarchical order in the DOM tree are sibling nodes. For example, <code>&lt;div&gt;</code> and <code>&lt;a&gt;</code> elements in the above example are siblings.</p>
</li>
<li><p><strong>Leaf nodes</strong>: The text inside of elements are leaf nodes. This is because they cannot have children nodes of their own.</p>
</li>
</ul>
<h2 id="heading-htmlcollection-vs-nodelist">HTMLCollection vs nodeList</h2>
<p>To manipulate the DOM tree, you need a way to select individual items or a collection of items in it.</p>
<p>You can use a programming language like JavaScript to select an item or a collection of items in the DOM tree by using a few methods provided by the DOM.</p>
<p>The methods <code>getElementById()</code> and <code>querySelector()</code> can select individual items. The methods <code>getElementsByClassName()</code>, <code>getElementsByTagName()</code>, or <code>querySelectorAll()</code> can select a collection of items.</p>
<p>In the DOM tree, we can either get an HTMLCollection or a NodeList based on the method used to select a collection of items. The <code>getElementsByClassName()</code> and <code>getElementsByTagName()</code> methods return HTMLCollections, while <code>querySelectorAll</code> returns a nodeList.</p>
<p>HTMLCollection and nodeList share some similarities and differences. They're similar in the following ways:</p>
<ul>
<li><p>They are array-like objects.</p>
</li>
<li><p>They are collections of items.</p>
</li>
<li><p>They can be converted into an array by using the <code>Array.from()</code> method.</p>
</li>
<li><p>They both have a zero-based indexing.</p>
</li>
<li><p>They can both be iterated over with a for...loop.</p>
</li>
<li><p>They have a length property.</p>
</li>
<li><p>They do not have array methods available to them.</p>
</li>
</ul>
<p>Below is a sample HTML document and JavaScript code to emphasize these similarities:</p>
<pre><code class="lang-html"><span class="hljs-comment">&lt;!-- html documant --&gt;</span>

<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item one<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item two<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item three<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item four<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> listItemsHtmlCollection = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"li"</span>)
<span class="hljs-built_in">console</span>.log(listItemsHtmlCollection) <span class="hljs-comment">// HTMLCollection(4) [li, li, li, li]</span>

<span class="hljs-keyword">const</span> listItemsNodeList = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"li"</span>)
<span class="hljs-built_in">console</span>.log(listItemsNodeList) <span class="hljs-comment">// NodeList(4) [li, li, li, li]</span>
</code></pre>
<p>You can see from the above that while the <code>getElementsByTagName</code> returns an HTMLCollection with items matching the <code>&lt;li&gt;</code> tag specified, the <code>querySelectorAll</code> returns a nodeList.</p>
<p>Now, let's use a for...loop to iterate on both collections:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; listItemsHtmlCollection.length; i++) {
    listItemsHtmlCollection[i].style.color = <span class="hljs-string">'red'</span>
}

<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; listItemsHtmlCollection.length; i++) {
    listItemsHtmlCollection[i].style.color = <span class="hljs-string">'red'</span>
}
</code></pre>
<p>In both instances the color of the text will be changed to red.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--145-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Now let's delete the for...loop iteration and use an array method on map to iterate over both collections:</p>
<pre><code class="lang-javascript">listItemsHtmlCollection.map( <span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> element.style.color = <span class="hljs-string">'red'</span> )
listItemsNodeList.map( <span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> element.style.color = <span class="hljs-string">'red'</span> )
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--146-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To use the map array method successfully, you have to convert both items to an array with the <code>Array.from()</code> method like this:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">Array</span>.from(listItemsHtmlCollection).map( <span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> element.style.color = <span class="hljs-string">'red'</span> )
<span class="hljs-built_in">Array</span>.from(listItemsNodeList).map( <span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> element.style.color = <span class="hljs-string">'red'</span> )
</code></pre>
<p>There are two major ways in which HTMLCollection and a nodeList differ from one another. They are:</p>
<ul>
<li><p>A nodeList comes with some inbuilt methods and properties not available in an HTMLCollection. The methods include the <code>forEach()</code> and the <code>entries</code> methods to iterate over a nodeList. The properties include the keys property and the value property.</p>
</li>
<li><p>An HTMLCollection is always live, while a nodeList can either be live or static. A collection of nodes is live if a change in the DOM tree updates the collection automatically. If a change in the DOM tree does not affect the collection, then it is static. DOM changes can be the addition of a new node or the removal of an existing node. DOM methods such as <code>getElementById()</code> and <code>getElementsByClassName()</code> return HTMLCollections, which is always live. The <code>querySelectorAll()</code> method returns a static nodeList.</p>
</li>
</ul>
<h2 id="heading-dom-html-methods">DOM HTML Methods</h2>
<p>The DOM level 1 core, Dom level 2 core, and Dom level 3 core introduced several methods that allow web developers to manipulate the DOM tree. Some of these methods are the following:</p>
<h3 id="heading-the-createelement-dom-method">The <code>createElement()</code> DOM method</h3>
<p>The <code>createElement()</code> method creates an element of the type specified as its argument.</p>
<pre><code class="lang-html">//html document

<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item one<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item two<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item three<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item four<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-comment">//select the parent element</span>
<span class="hljs-keyword">const</span> list = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'ul'</span>)
<span class="hljs-comment">//create a new element</span>
<span class="hljs-keyword">const</span> listItem = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'li'</span>)
<span class="hljs-comment">//make the newly created element a child of the parent</span>
list.appendChild(<span class="hljs-string">'listItem'</span>)
<span class="hljs-built_in">console</span>.log(list)
</code></pre>
<p>Now check the console for the list console logged. You'll see that there are five <code>&lt;li&gt;</code> elements now within the <code>&lt;ul&gt;</code> parent element.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--147--1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-createtextnode-dom-method">The <code>createTextNode()</code> DOM method</h3>
<p>The <code>createTextNode()</code> method creates a text node with the string specified as its argument. Let's add text to the <code>&lt;li&gt;</code> element we created above.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> listText = <span class="hljs-built_in">document</span>.createTextNode(<span class="hljs-string">"item five"</span>)
listItem.appendChild(listText)
</code></pre>
<p>Now save your JavaScript file and reload your webpage.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--149-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-appendchild-dom-method">The <code>appendChild()</code> DOM method</h3>
<p>The <code>appendChild()</code> method adds a node to the end of the list of children of a parent node.</p>
<p>If the specified child is an existing node in the document, <code>appendChild()</code> moves it from its current position on the DOM tree to the new position. We used the method earlier to make our newly created <code>&lt;li&gt;</code> element a child of the <code>&lt;ul&gt;</code> element.</p>
<h3 id="heading-the-getelementbyid-dom-method">The <code>getElementById()</code> DOM method</h3>
<p>This method selects and returns the element whose ID is specified within it as a argument. If no such element exists, the method returns null. Let's add an <em>id</em> attribute to our <code>&lt;ul&gt;</code> element in the HTML document and give it a red border.</p>
<pre><code class="lang-html">//html document

<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"ulList"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item one<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item two<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item three<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item four<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>


    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> ulList = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"ulList"</span>) 
ulList.style.border = <span class="hljs-string">'2px solid red'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--150-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-getelementsbyclassname-dom-method">The <code>getElementsByClassName()</code> DOM method</h3>
<p>The <code>getElementsByClassName()</code> method selects all elements with the specified class name and returns them as an HTMLCollection in the order they appear on the DOM tree.</p>
<p>You can access individual elements in the HTMLCollection by their index number. Let's add a class attribute to the first two <code>&lt;li&gt;</code> elements in our HTML document and change their text color to red like this:</p>
<pre><code class="lang-html">//html document

<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Document<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"style.css"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"ulList"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"itemOneAndTwo"</span>&gt;</span>item one<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"itemOneAndTwo"</span>&gt;</span>item two<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item three<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>item four<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>


    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-comment">//select by elements one and two by their class name</span>
<span class="hljs-keyword">const</span> itemOneAndTwo = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"itemOneAndTwo"</span>)
<span class="hljs-comment">//change text color to red with use of index</span>
itemOneAndTwo[<span class="hljs-number">0</span>].style.color = <span class="hljs-string">'red'</span>
itemOneAndTwo[<span class="hljs-number">1</span>].style.color = <span class="hljs-string">'red'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--151-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-getelementsbytagname-dom-method">The <code>getElementsByTagName()</code> DOM method</h3>
<p>The <code>getElementsByTagName()</code> method returns an HTMLCollection of all the elements with the tag name specified as its argument, in the order they appear on the DOM tree.</p>
<p>Let's select the <code>&lt;li&gt;</code> elements with the <code>getElementsBytagName()</code> method and change their font style to italic.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> liTags = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"li"</span>) 
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; liTags.length; i++) {
    liTags[i].style.fontStyle = <span class="hljs-string">'italic'</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--152-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-queryselector-dom-method">The <code>querySelector()</code> DOM method</h3>
<p>The <code>querySelector()</code> method accepts any CSS string selector as an argument. It then uses the specified selector to select the first within the document that matches that specified selector.</p>
<p>Let's change select our first two <code>&lt;li&gt;</code> elements with the <code>querySelector()</code> method and change their text color back to black.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> querySelectItem = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"itemOneAndTwo"</span>)
querySelectItem.style.color = <span class="hljs-string">'black'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--153-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Notice that only the first list item has had its color changed to black.</p>
<h3 id="heading-the-queryselectorall-dom-method">The <code>querySelectorAll()</code> DOM method</h3>
<p>The <code>querySelectorAll()</code> method, just like the <code>querySelector</code> method, accepts any CSS string selector as its argument. It then uses the specified CSS string selector to select all elements that match that specified selector, put them in a nodeList, and return that nodeList.</p>
<p>Now, let's use it to change all the text in out list items to green.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> querySelectAllItems = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"li"</span>)
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; querySelectAllItems.length; i++) {
    querySelectAllItems[i].style.color = <span class="hljs-string">'green'</span>
}
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--154-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-setattribute-dom-method">The <code>setAttribute()</code> DOM method</h3>
<p>The <code>setAttribute()</code> method adds a new attribute name to an element. If an attribute with that name is already present in the element, its value will change to that of the value set in the argument.</p>
<p>The method accepts two arguments. The first argument is the name of the attribute you want to create. The second argument is the value to set on the attribute, which is always a string.</p>
<p>Let's use it to give our third item a class attribute and change the text color to black.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> itemThree = querySelectAllItems[<span class="hljs-number">2</span>] 
itemThree.setAttribute(<span class="hljs-string">"class"</span>, <span class="hljs-string">"attributeValue"</span>)  
<span class="hljs-keyword">const</span> attributeValue = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.attributeValue'</span>)
attributeValue.style.color = <span class="hljs-string">'black'</span>
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/06/Screenshot--155-.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-the-removeattribute-dom-method">The <code>removeAttribute()</code> DOM method</h3>
<p>The <code>removeAttribute()</code> method removes a specified attribute. It takes in the name of the attribute to be removed as its argument. Let's remove the <em>id</em> attribute from the <code>&lt;ul&gt;</code> parent element and use the removed id to removed its red border.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-comment">//remove attribute</span>
ul.removeAttribute(<span class="hljs-string">'id'</span>)
ul.style.border = <span class="hljs-string">'none'</span>
</code></pre>
<p>Now save your JavaScript file and reload your web page. Notice that the borders are still there. If you check the console you will see an error message stating that <em>ul</em> is no longer defined.</p>
<h3 id="heading-the-contains-dom-method">The <code>contains()</code> DOM method</h3>
<p>The <code>contains()</code> method returns true if a node is a descendant of a node and returns false otherwise.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">--HTML</span> <span class="hljs-attr">document--</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>   
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Heading<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span> 
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>
<span class="hljs-keyword">const</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'body'</span>)
<span class="hljs-keyword">const</span> h1Element = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'h1'</span>)
<span class="hljs-built_in">console</span>.log( body.contains(h1Element) ) <span class="hljs-comment">// true</span>
</code></pre>
<h3 id="heading-the-item-dom-method">The <code>item()</code> DOM method</h3>
<p>The <code>item()</code> method returns the item specified at the index specified as its argument when used on a collection.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">--HTML</span> <span class="hljs-attr">document--</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>   
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>
<span class="hljs-keyword">const</span> pElements = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"p"</span>) 
<span class="hljs-built_in">console</span>.log(pElements.item(<span class="hljs-number">0</span>)) <span class="hljs-comment">// &lt;p&gt;&lt;/p&gt;</span>
</code></pre>
<h3 id="heading-the-haschildnodes-dom-method">The <code>hasChildNodes()</code> DOM method</h3>
<p>The <code>hasChildNodes</code> method returns true if the element it is called on has child nodes within it and returns false otherwise.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">--HTML</span> <span class="hljs-attr">document--</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>   
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//javascript content</span>

<span class="hljs-keyword">const</span> body = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"body"</span>)

<span class="hljs-built_in">console</span>.log(body.hasChildNodes()) <span class="hljs-comment">// true</span>
</code></pre>
<h2 id="heading-what-are-dom-events">What are DOM Events?</h2>
<p>To make our web page logically interactive by initiating automatic responses or incidents on the web page, we need Events.</p>
<p>DOM events are:</p>
<blockquote>
<p>actions or occurrences that happen in the system you are programming, which the system tells you about so your code can react to them. (Source: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_objects">MDN</a>)</p>
</blockquote>
<p>A common example of an event is when a user clicks a submit button in a form, which then submits the data input by the user as a response to the click.</p>
<p>Another example is when a user clicks on a menu icon, which then triggers a drop-down navigation or options.</p>
<p>You can use scripting languages such as JavaScript to register event handlers or listeners on elements inside the DOM tree, which runs when the specified event fires.</p>
<p>An event handler is a:</p>
<blockquote>
<p>block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires. When such a block of code is defined to run in response to an event, we say we are <strong>registering an event handler</strong>. (Source: <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_objects">MDN</a>)</p>
</blockquote>
<p>Examples of events used on elements in the DOM tree include:</p>
<ul>
<li><p><strong>click</strong>: A click event is a mousedown or mouseup over an element on a webpage.</p>
</li>
<li><p><strong>keypress</strong>: A keypress event occurs when keys on the keyboard are pressed.</p>
</li>
<li><p><strong>mouseover</strong>: A mouseover event occurs when the pointing device is moved onto an element.</p>
</li>
<li><p><strong>dblclick</strong>: A dblclick occurs when there is a double-click event over an element on a webpage.</p>
</li>
<li><p><strong>submit</strong>: A submit event occurs when a form is submitted.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The DOM is the backbone of modern web dynamism. It represents every piece of a web document as an object and provides programming languages with the necessary methods to manipulate and modify each piece.</p>
<p>If you enjoyed this write-up, you should give me a <a target="_blank" href="https://twitter.com/activus_d"><em>shoutout</em></a>.</p>
<h3 id="heading-references-and-further-reading">References and Further Reading</h3>
<ol>
<li><p><a target="_blank" href="https://dom.spec.whatwg.org/">https://dom.spec.whatwg.org/</a></p>
</li>
<li><p><a target="_blank" href="https://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html">https://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-core.html</a></p>
</li>
<li><p><a target="_blank" href="https://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html">https://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html.html</a></p>
</li>
<li><p><a target="_blank" href="https://www.w3.org/TR/DOM-Level-2-HTML/">https://www.w3.org/TR/DOM-Level-2-HTML/</a></p>
</li>
<li><p><a target="_blank" href="https://www.w3.org/TR/DOM-Level-3-Core/core.html">https://www.w3.org/TR/DOM-Level-3-Core/core.html</a></p>
</li>
</ol>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What is the DOM? Document Object Model Meaning in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ If you have just started learning JavaScript, you might have heard of the DOM. But what is it exactly? In this article, I will explain what the DOM is and provide some JavaScript code examples.  We will take a look at how to select elements from an H... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-the-dom-document-object-model-meaning-in-javascript/</link>
                <guid isPermaLink="false">66b8da868cd1c2aa053d49c5</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Jessica Wilkins ]]>
                </dc:creator>
                <pubDate>Mon, 27 Sep 2021 16:23:19 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/09/joan-gamell-ZS67i1HLllo-unsplash-1.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you have just started learning JavaScript, you might have heard of the DOM. But what is it exactly?</p>
<p>In this article, I will explain what the DOM is and provide some JavaScript code examples. </p>
<p>We will take a look at how to select elements from an HTML document, how to create elements, how to change inline CSS styles, and how to listen for events. </p>
<h2 id="heading-what-is-the-dom">What is the DOM?</h2>
<p>DOM stands for Document Object Model. It is a programming interface that allows us to create, change, or remove elements from the document. We can also add events to these elements to make our page more dynamic. </p>
<p>The DOM views an HTML document as a tree of nodes. A node represents an HTML element. </p>
<p>Let's take a look at this HTML code to better understand the DOM tree structure. </p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"ie=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>DOM tree structure<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>DOM tree structure<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Learn about the DOM<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Our document is called the root node and contains one child node which is the <code>&lt;html&gt;</code> element. The <code>&lt;html&gt;</code> element contains two children which are the <code>&lt;head&gt;</code> and <code>&lt;body&gt;</code> elements. </p>
<p>Both the <code>&lt;head&gt;</code> and <code>&lt;body&gt;</code> elements have children of their own. </p>
<p>Here is another way to visualize this tree of nodes. </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Document.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We can access these elements in the document and make changes to them using JavaScript. </p>
<p>Let's take a look at a few examples of how we can work with the DOM using JavaScript.</p>
<h2 id="heading-how-to-select-elements-in-the-document">How to Select Elements in the Document</h2>
<p>There are a few different methods for selecting an element in the HTML document.</p>
<p>In this article, we will focus on three of those methods:</p>
<ul>
<li><code>getElementById()</code></li>
<li><code>querySelector()</code> </li>
<li><code>querySelectorAll()</code></li>
</ul>
<h3 id="heading-getelementbyid"><code>getElementById()</code></h3>
<p>In HTML, <code>id</code>s are used as unique identifiers for the HTML elements. This means you cannot have the same <code>id</code> name for two different elements.</p>
<p>This would be incorrect:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"para"</span>&gt;</span>This is my first paragraph.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"para"</span>&gt;</span>This is my second paragraph.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p>You would have to make sure those <code>id</code>s are unique like this:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"para1"</span>&gt;</span>This is my first paragraph.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"para2"</span>&gt;</span>This is my second paragraph.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<p> In JavaScript, we can grab an HTML tag by referencing the <code>id</code> name.</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"id name goes here"</span>)
</code></pre>
<p>This code tells the computer to get the <code>&lt;p&gt;</code> element with the <code>id</code> of <code>para1</code> and print the element to the console.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> paragraph1 = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"para1"</span>);
<span class="hljs-built_in">console</span>.log(paragraph1);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Screen-Shot-2021-09-26-at-2.25.49-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If we wanted to just read the content of the paragraph, then we can use the <code>textContent</code> property inside the <code>console.log()</code>. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> paragraph1 = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"para1"</span>);
<span class="hljs-built_in">console</span>.log(paragraph1.textContent);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Screen-Shot-2021-09-26-at-2.35.31-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-queryselector"><code>querySelector()</code></h3>
<p>You can use this method to find elements with one or more CSS selectors. </p>
<p>I have created this HTML example of my favorite tv shows:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Favorite TV shows<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"list"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Golden Girls<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Archer<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Rick and Morty<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>The Crown<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</code></pre>
<p>If I wanted to find and print to the console the <code>h1</code> element, then I could use that tag name inside the <code>querySelector()</code>. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> h1Element = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"h1"</span>);
<span class="hljs-built_in">console</span>.log(h1Element);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Screen-Shot-2021-09-26-at-3.15.59-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If I wanted to target the <code>class="list"</code> to print out the unordered list to the console, then I would use <code>.list</code> inside the  <code>querySelector()</code>. </p>
<p>The <code>.</code> before <code>list</code> tells the computer to target a class name. If you wanted to target an <code>id</code> then you would use a <code>#</code> symbol before the name. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> list = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".list"</span>);
<span class="hljs-built_in">console</span>.log(list);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Screen-Shot-2021-09-26-at-3.22.45-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-queryselectorall"><code>querySelectorAll()</code></h3>
<p>This method finds all of the elements that match the CSS selector and returns a list of all of those nodes. </p>
<p>If I wanted to find all of the <code>&lt;li&gt;</code> items in our example, I could use the <code>&gt;</code> child combinator to find all of the children of the <code>&lt;ul&gt;</code>. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> listItems = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"ul &gt; li"</span>);
<span class="hljs-built_in">console</span>.log(listItems);
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Screen-Shot-2021-09-26-at-3.30.46-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>If we wanted to print out the actual <code>&lt;li&gt;</code> items with the tv shows, we can use a <code>forEach()</code> to loop over the NodeList and print out each item.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> listItems = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"ul &gt; li"</span>);

listItems.forEach(<span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(item);
});
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Screen-Shot-2021-09-26-at-3.42.13-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-add-new-elements-to-the-document">How to Add New Elements to the Document</h2>
<p>We can use the <code>document.createElement()</code> to add new elements to the DOM tree. </p>
<p>Let's take a look at this example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Reasons why I love freeCodeCamp:<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
</code></pre>
<p>Right now, I just have an <code>&lt;h1&gt;</code> tag on the page. But I want to add a list of reasons why I love freeCodeCamp underneath that <code>&lt;h1&gt;</code> tag using JavaScript. </p>
<p>We can first create an <code>&lt;ul&gt;</code> element using <code>document.createElement()</code>. I will assign that to a variable called <code>unorderedList</code>. </p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> unorderedList = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"ul"</span>);
</code></pre>
<p>Then we need to add that <code>&lt;ul&gt;</code> element to the document using the <code>appendChild()</code> method. </p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.body.appendChild(unorderedList);
</code></pre>
<p>The next part is to add a couple of <code>&lt;li&gt;</code> elements inside the <code>&lt;ul&gt;</code> element using the <code>createElement()</code> method.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> listItem1 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"li"</span>);

<span class="hljs-keyword">let</span> listItem2 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"li"</span>);
</code></pre>
<p>Then we can use the  <code>textContent</code> property to add the text for our list items. </p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> listItem1 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"li"</span>);
listItem1.textContent = <span class="hljs-string">"It's free"</span>;

<span class="hljs-keyword">let</span> listItem2 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"li"</span>);
listItem2.textContent = <span class="hljs-string">"It's awesome"</span>;
</code></pre>
<p>The last part is to use the <code>appendChild()</code> method so the list items can be added to the unordered list. </p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> listItem1 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"li"</span>);
listItem1.textContent = <span class="hljs-string">"It's free"</span>;
unorderedList.appendChild(listItem1);

<span class="hljs-keyword">let</span> listItem2 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"li"</span>);
listItem2.textContent = <span class="hljs-string">"It's awesome"</span>;
unorderedList.appendChild(listItem2);
</code></pre>
<p>This is what the code looks like all together.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> unorderedList = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"ul"</span>);
<span class="hljs-built_in">document</span>.body.appendChild(unorderedList);

<span class="hljs-keyword">let</span> listItem1 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"li"</span>);
listItem1.textContent = <span class="hljs-string">"It's free"</span>;
unorderedList.appendChild(listItem1);

<span class="hljs-keyword">let</span> listItem2 = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">"li"</span>);
listItem2.textContent = <span class="hljs-string">"It's awesome"</span>;
unorderedList.appendChild(listItem2);
</code></pre>
<p>This is what the output looks like on the page:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Screen-Shot-2021-09-26-at-4.21.55-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-how-to-use-the-style-property-to-change-inline-css-styles">How to Use the Style Property to Change Inline CSS Styles</h2>
<p>The <code>style</code> property gives you the ability to change the CSS in your HTML document. </p>
<p>In this example, we are going to change the <code>h1</code> text from black to blue using the <code>style</code> property. </p>
<p>Here is our HTML.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>I was changed to blue using JavaScript<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
</code></pre>
<p>We first need to grab the <code>h1</code> tag using the <code>querySelector()</code> method.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> h1 = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"h1"</span>);
</code></pre>
<p>We then use <code>h1.style.color</code> to change the <code>h1</code> text from black to blue.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> h1 = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"h1"</span>);
h1.style.color = <span class="hljs-string">"blue"</span>;
</code></pre>
<p>This is what the result looks like in the browser:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/09/Screen-Shot-2021-09-26-at-4.33.44-PM.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>You can use this <code>style</code> property to change a number of CSS inline styles including <code>background-color</code>, <code>border-style</code>, <code>font-size</code> and more. </p>
<h2 id="heading-how-to-use-addeventlistener-to-listen-for-events-on-the-page">How to Use addEventListener() to Listen for Events on the Page</h2>
<p>This method allows you to attach an event to an HTML element like a button. </p>
<p>In this example, when the user clicks on the button, an alert message will pop up. </p>
<p>In our HTML, we have a button element with the <code>id</code> of <code>btn</code>.</p>
<pre><code class="lang-html">  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"btn"</span>&gt;</span>Show alert<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>We can target that element in our JavaScript using the <code>getElementById()</code> method and assigning that to the variable called <code>button</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"btn"</span>);
</code></pre>
<p>The <code>addEventListener()</code> takes in an event type and a function. The event type will be a <code>click</code> event and the function will trigger the alert message. </p>
<p>This is the code to add the event listener to the <code>button</code> variable.</p>
<pre><code class="lang-js">button.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  alert(<span class="hljs-string">"Thank you for clicking me"</span>);
});
</code></pre>
<p>This is the complete code where you can click the button and the alert message will pop up:</p>
<div class="embed-wrapper">
        <iframe width="100%" height="350" src="https://codepen.io/jessica-wilkins/embed/abwQwPb?editors=1010" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="CodePen embed" scrolling="no" allowtransparency="true" allowfullscreen="true" loading="lazy"></iframe></div>
<h2 id="heading-how-to-use-the-dom-in-real-world-projects">How to Use the DOM in Real World Projects</h2>
<p>That was brief introduction to some of the DOM methods you can use. There are plenty more examples that we didn't cover in this article. </p>
<p>If you want to start building beginner JavaScript projects and work with the DOM, then I would suggest looking at my <a target="_blank" href="https://www.freecodecamp.org/news/javascript-projects-for-beginners/">40 JavaScript Projects for Beginners</a> article.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>DOM stands for Document Object Model and is a programming interface that allows us to create, change or remove elements from the document. We can also add events to these elements to make our page more dynamic. </p>
<p>You can select elements in JavaScript using methods like <code>getElementById(), querySelector()</code>, and <code>querySelectorAll()</code>.</p>
<p>If you want to add new elements to the document you can use <code>document.createElement()</code>. </p>
<p>You can also change the inline CSS styles of elements using the <code>style</code> property.</p>
<p>If you want to add events to elements like buttons then you can use the <code>addEventListener()</code>. </p>
<p>I hope you enjoyed this article and best of luck on your JavaScript journey. </p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The DOM Explained for Beginners – How the Document Object Model Works ]]>
                </title>
                <description>
                    <![CDATA[ When I started out as a web developer, people often threw around the term "DOM" in the industry. Every JavaScript tutorial mentioned it, but I didn't know what it meant. Fast forward two years, and now that I know what it's all about, I am going to e... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dom-explained-everything-you-need-to-know-about-the-document-object-model/</link>
                <guid isPermaLink="false">66d4617a73634435aafceffe</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kingsley Ubah ]]>
                </dc:creator>
                <pubDate>Mon, 17 May 2021 17:45:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2021/05/DOM--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When I started out as a web developer, people often threw around the term "DOM" in the industry. Every JavaScript tutorial mentioned it, but I didn't know what it meant.</p>
<p>Fast forward two years, and now that I know what it's all about, I am going to explain what the <strong>Document Object Model</strong> is in plain and simple English.</p>
<h2 id="heading-what-is-the-dom">What is the DOM?</h2>
<p>Imagine this: you have the TV on. You don't like the show that's being streamed, and you want to change it. You also want to increase its volume.</p>
<p>To do that, there has to be a way for you to interact with your television. And what do you use to do that?</p>
<p><strong>A remote</strong>.</p>
<p>The remote serves as the <strong>bridge</strong> which allows you interact with your television.</p>
<p>You make the TV <strong>active</strong> and <strong>dynamic</strong> via the remote. And in the same way, JavaScript makes the HTML page active and dynamic via the <strong>DOM</strong>.</p>
<p>Just like how the television can't do much for itself, JavaScript doesn't do much more than allow you to‌‌ perform some calculations or work with basic strings.</p>
<p>So to make an HTML document more interactive and dynamic, the script‌‌ needs to be able to access the contents of the document and it also needs to know when the user is interacting with it.‌‌</p>
<p>It does this by communicating with the browser using the properties, methods, and events in the interface called the Document Object Model, or DOM.</p>
<p>For example, say that you want a button to change colours when it gets clicked or an image to slide when the mouse hovers over it. First, you need to reference those elements from your JavaScript.</p>
<p>The DOM is a tree-like representation of the web page that gets loaded into the browser.</p>
<p>It represents the web page using a‌‌ series of objects. The main object is the document object, which in turn houses other objects which also house their own objects, and so on.</p>
<h3 id="heading-the-document-object">The Document Object</h3>
<p>This is the top most object in the DOM. It has <strong>properties</strong> and <strong>methods</strong> which you can use to get information about the document using a rule known as dot notation.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/05/table.png" alt="The Document Object Model Tree" width="600" height="400" loading="lazy"></p>
<p><em>Document Tree. Source https://w3.org</em></p>
<p>After the document, you place a dot followed by a property or method.</p>
<p>Let's look at a simple demonstration that shows how a script can access the contents of an HTML document through the DOM:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Login to your account<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>‌‌
<span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">name</span>=<span class="hljs-string">”LoginFrm”</span> <span class="hljs-attr">action</span>=<span class="hljs-string">”login.php”</span> <span class="hljs-attr">method</span>=<span class="hljs-string">”post”</span>&gt;</span>‌‌Username 
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”text”</span> <span class="hljs-attr">name</span>=<span class="hljs-string">”txtUsername”</span> <span class="hljs-attr">size</span>=<span class="hljs-string">”15”/</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span>‌‌Password 
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”password”</span> <span class="hljs-attr">name</span>=<span class="hljs-string">”numPassword”</span> <span class="hljs-attr">size</span>=<span class="hljs-string">”15”/</span>&gt;</span> <span class="hljs-tag">&lt;<span class="hljs-name">br</span>/&gt;</span>‌‌
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">”submit”</span> <span class="hljs-attr">value</span>=<span class="hljs-string">”Log</span> <span class="hljs-attr">In</span>” /&gt;</span>‌‌
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>‌‌
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> New user? <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">”register.php”</span>&gt;</span> Register here<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">”lostPassword.php”</span>&gt;</span> Retrieve password <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span> 
<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> username = <span class="hljs-built_in">document</span>.LoginFrm.txtUsername.value <span class="hljs-comment">//Gets the username input</span>
</code></pre>
<p>Alright. That's the HTML a login form. You can access all of these elements in JavaScript with the set of properties and methods the DOM API provides. But what are those methods?</p>
<p>In addition to the property and method included in the code snippet, let's take a look at some of the other popular ones:</p>
<h3 id="heading-the-queryselectorall-method">The querySelectorAll() method</h3>
<p>You use this method to access one or more elements from the DOM that matches one or more CSS selectors:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> first div <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> first paragraph <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> second div <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> second paragraph <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> another div <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> paragraphs = <span class="hljs-built_in">document</span>.querySelectorAll( <span class="hljs-string">'p'</span> );
paragraphs.forEach(<span class="hljs-function"><span class="hljs-params">paragraph</span> =&gt;</span> paragraph.display = <span class="hljs-string">'none'</span>)
</code></pre>
<h3 id="heading-the-createelement-method">The createElement() method</h3>
<p>You use this method to create a specified element and insert it into the DOM:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>first div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> first paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>second div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>second paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>another div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> thirdParagraph = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'p'</span>);
</code></pre>
<h3 id="heading-the-getelementbyid-method">The getElementById() method</h3>
<p>You use this method to get an element from the document by its unique id attribute:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">'first'</span>&gt;</span> first div <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> first paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>second div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> second paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>another div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> firstDiv = getElementById(<span class="hljs-string">"first"</span>)
</code></pre>
<h3 id="heading-the-getelementsbytagname-method">The getElementsByTagname() method</h3>
<p>You use this method to access one or more elements by their HTML tag name:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> first div <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span> first paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span> second div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>second paragraph<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>another div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js">divs = <span class="hljs-built_in">document</span>.getElementByTagname(<span class="hljs-string">"div"</span>);
</code></pre>
<h3 id="heading-the-appendchild-element">The appendChild() element</h3>
<p>You use this element to access one or more elements by their HTML tag name.</p>
<p>It adds an element as the last child to the HTML element that invokes this method.</p>
<p>The child to be inserted can be either a newly created element or an already existing one. If it already exists, it will be moved from its previous position to the position of the last child.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>
     &lt;<span class="hljs-attr">h2</span>&gt;</span>Mangoes<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> p = <span class="hljs-built_in">document</span>.createElement( <span class="hljs-string">'p'</span> );
<span class="hljs-keyword">var</span> h2 = <span class="hljs-built_in">document</span>.querySelector( <span class="hljs-string">'h2'</span> );
<span class="hljs-keyword">var</span> div = <span class="hljs-built_in">document</span>.querySelector( <span class="hljs-string">'div'</span> );
h1.textContent = <span class="hljs-string">'Mangoes are great...'</span>
div.appendChild(<span class="hljs-string">'p'</span>);
</code></pre>
<h3 id="heading-the-innerhtml-property">The innerHTML property</h3>
<p>You use this property to access the text content of an element.</p>
<h3 id="heading-the-addeventlistener-property">The addEventListener() property</h3>
<p>This property attaches an event listener to your element.</p>
<p>It takes a callback which will run when that event is triggered.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Click to submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>‌‌
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> btn = <span class="hljs-built_in">document</span>.querySelector( <span class="hljs-string">'button'</span> );‌‌
btn.addEventListener( <span class="hljs-string">'click'</span> ,foo);‌‌
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">foo</span>(<span class="hljs-params"></span>) </span>{ alert( <span class="hljs-string">'submitted!'</span> ); 
                  btn.innerHTML = <span class="hljs-string">''</span>;
          }
</code></pre>
<h3 id="heading-the-replacechild-property">The replaceChild() property</h3>
<p>This property replaces one child element with another new or existing child element. If it already exists, it will be moved from its previous position to the position of the last child.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>‌‌
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Mangoes‌<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>‌
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> h2 = <span class="hljs-built_in">document</span>.createElement( <span class="hljs-string">'h2'</span> );‌‌
<span class="hljs-keyword">var</span> h1 = <span class="hljs-built_in">document</span>.querySelector( <span class="hljs-string">'h1'</span> );‌‌
<span class="hljs-keyword">var</span> div = <span class="hljs-built_in">document</span>.querySelector( <span class="hljs-string">'div'</span> );‌‌
h2.textContent = <span class="hljs-string">'Apple'</span>;‌‌
div.insertBefore(h1, h2);
</code></pre>
<h3 id="heading-the-setattribute-method">The setAttribute() method</h3>
<p>You use this method to set or change the value of an element's attribute.</p>
<p>Suppose we have an attribute “id” containing the value “favourite.”‌‌ But we want to change the value to “worst” Here's how you can do that with code:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>‌‌
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">id</span>=<span class="hljs-string">'favourite'</span>&gt;</span>Mangoes‌‌<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> h1 = <span class="hljs-built_in">document</span>.querySelector( <span class="hljs-string">'h1'</span> );
h1.setAttribute(div, <span class="hljs-string">'worst'</span>);
</code></pre>
<h3 id="heading-the-node-method">The node method</h3>
<p>Every element in an HTML page is known as a node.</p>
<p>You can access any element by using the following properties with the node object:</p>
<ul>
<li><p><code>node.childNodes</code> – accesses the child nodes of a selected parent‌‌</p>
</li>
<li><p><code>node.firstChild</code> – accesses the first child of a selected parent‌‌</p>
</li>
<li><p><code>node.lastChild</code> – accesses the last child of a selected parent.‌‌</p>
</li>
<li><p><code>node.parentNode</code> – accesses the parent of a selected child node.‌‌</p>
</li>
<li><p><code>node.nextSibling</code> – accesses the next consecutive element (sibling) of a selected element.‌‌</p>
</li>
<li><p><code>node.previousSibling</code> – accesses the previous element (sibling) of a selected element</p>
</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id-</span>“<span class="hljs-attr">list</span>”&gt;</span>‌‌
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>= <span class="hljs-string">”about.html”‌‌class</span> = <span class="hljs-string">”list_one”</span>&gt;</span> About‌‌<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>‌‌
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>= <span class="hljs-string">”policy.html”</span>&gt;</span> Policy‌‌<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/ <span class="hljs-attr">li</span>&gt;</span>‌‌
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>= <span class="hljs-string">”map.html”</span>&gt;</span> Map‌‌<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/ <span class="hljs-attr">li</span>&gt;</span>‌‌
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>= <span class="hljs-string">”Refund.html”</span>&gt;</span> Refund‌‌<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>‌‌
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
</code></pre>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> list = <span class="hljs-built_in">document</span>.getElementsById( “site-list” )‌‌
<span class="hljs-keyword">var</span> firstItem = list‌‌.childNodes[<span class="hljs-number">0</span>].childNodes[<span class="hljs-number">0</span>];
</code></pre>
<h2 id="heading-summary">Summary</h2>
<p>The DOM is a top down representation of all the elements that make up a web page. It's the interface through which your script interacts with your HTML.</p>
<p>There are many properties and methods which you can use to get information about the DOM and manipulate it.</p>
<p>That's all for this article. I hope you learnt something worthwhile.</p>
<p>If you liked it, you can buy me some coffee <a target="_blank" href="https://ubahthebuilder.tech">here</a>.</p>
<p>Thank you and see you soon.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to the JavaScript DOM ]]>
                </title>
                <description>
                    <![CDATA[ By Gabriel Tanner The Javascript DOM (Document Object Model) is an interface that allows developers to manipulate the content, structure and style of a website. In this article, we will learn what the DOM is and how you can manipulate it using Javasc... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-introduction-to-the-javascript-dom-512463dd62ec/</link>
                <guid isPermaLink="false">66d45ede182810487e0ce186</guid>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 27 Mar 2019 18:19:32 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*QqW2LsIY0wf5BeDv" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Gabriel Tanner</p>
<p>The Javascript DOM (Document Object Model) is an interface that allows developers to manipulate the content, structure and style of a website. In this article, we will learn what the DOM is and how you can manipulate it using Javascript. This article can also be used as a reference for the basic DOM operations.</p>
<h3 id="heading-what-is-the-dom">What is the DOM?</h3>
<p>At the most basic level, a website consists of an HTML and CSS document. The browser creates a representation of the document known as Document Object Model (DOM). This document enables Javascript to access and manipulate the elements and styles of a website. The model is built in a tree structure of objects and defines:</p>
<ul>
<li>HTML elements as objects</li>
<li>Properties and events of the HTML elements</li>
<li>Methods to access the HTML elements</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/g42eKZ-RmFNQVN5EZ1lF2wj67VqIdX7DMk4Z" alt="Image" width="486" height="266" loading="lazy">
<em>HTML DOM model</em></p>
<p>The places of the elements are referred to as nodes. Not only elements get nodes but also the attributes of elements and text get their own node (attribute-nodes and text-nodes).</p>
<h3 id="heading-dom-document">DOM Document</h3>
<p>The DOM Document is the owner of all other objects in your webpage. That means if you want to access any object on your webpage you always have to start with the document. It also contains many important properties and methods that enable us to access and modify our website.</p>
<h3 id="heading-finding-html-elements">Finding HTML Elements</h3>
<p>Now that we understand what the DOM document is we can start getting our first HTML elements. There are many different ways to do so using the Javascript DOM here are the most common:</p>
<h4 id="heading-get-element-by-id">Get element by ID</h4>
<p>The <em>getElementById()</em> method is used to get a single element by its id. Let’s look at an example:</p>
<pre><code><span class="hljs-keyword">var</span> title = <span class="hljs-built_in">document</span>.getElementById(‘header-title’);
</code></pre><p>Here we get the element with the id of header-title and save it into a variable.</p>
<h4 id="heading-get-elements-by-class-name">Get elements by class name</h4>
<p>We can also get more than one object using the <em>getElementsByClassName()</em> method which returns an array of elements.</p>
<pre><code><span class="hljs-keyword">var</span> items = <span class="hljs-built_in">document</span>.getElementsByClassName(‘list-items’);
</code></pre><p>Here we get all items with the class <em>list-items</em> and save them into a variable.</p>
<h4 id="heading-get-element-by-tag-name">Get element by tag name</h4>
<p>We can also get our elements by tag name using the <em>getElementsByTagName()</em> method.</p>
<pre><code><span class="hljs-keyword">var</span> listItems = <span class="hljs-built_in">document</span>.getElementsByTagName(‘li’);
</code></pre><p>Here we get all <em>li</em> elements of our HTML document and save them into a variable.</p>
<h4 id="heading-queryselector">Queryselector</h4>
<p>The <em>querySelector()</em> method returns the first element that matches a specified <em>CSS selector.</em> That means that you can get elements by id, class, tag and all other valid CSS selectors. Here I just list a few of the most popular options.</p>
<p><strong>Get by id:</strong></p>
<pre><code><span class="hljs-keyword">var</span> header = <span class="hljs-built_in">document</span>.querySelector(‘#header’)
</code></pre><p><strong>Get by class:</strong></p>
<pre><code><span class="hljs-keyword">var</span> items = <span class="hljs-built_in">document</span>.querySelector(‘.list-items’)
</code></pre><p><strong>Get by tag:</strong></p>
<pre><code><span class="hljs-keyword">var</span> headings = <span class="hljs-built_in">document</span>.querySelector(‘h1’);
</code></pre><p><strong>Get more specific elements:</strong></p>
<p>We can also get more specific elements using <em>CSS Selectors</em>.</p>
<pre><code><span class="hljs-built_in">document</span>.querySelector(“h1.heading”);
</code></pre><p>In this example we search for a tag and a class at the same time and return the first element that passes the CSS Selector.</p>
<h4 id="heading-queryselectorall">Queryselectorall</h4>
<p>The <em>querySelectorAll()</em> method is completely the same as the <em>querySelector()</em> except that it returns all elements that fit the CSS Selector.</p>
<pre><code><span class="hljs-keyword">var</span> heading = <span class="hljs-built_in">document</span>.querySelectorAll(‘h1.heading’);
</code></pre><p>In this example, we get all <em>h1</em> tags that have a class of <em>heading</em> and store them in an array.</p>
<h3 id="heading-changing-html-elements">Changing HTML Elements</h3>
<p>The HTML DOM allows us to change the content and style of an HTML element by changing its properties.</p>
<h4 id="heading-changing-the-html">Changing the HTML</h4>
<p>The innerHTML property can be used to change the content of an HTML element.</p>
<pre><code><span class="hljs-built_in">document</span>.getElementById(“#header”).innerHTML = “Hello World!”;
</code></pre><p>In this example we get the element with an id of header and set the inner content to “Hello World!”.</p>
<p>InnerHTML can also be used to put tags in another tag.</p>
<pre><code><span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"div"</span>).innerHTML = <span class="hljs-string">"&lt;h1&gt;Hello World!&lt;/h1&gt;"</span>
</code></pre><p>Here we put a h1 tag into all already existing div.</p>
<h4 id="heading-changing-a-value-of-an-attribute"><strong>Changing a value of an attribute</strong></h4>
<p>You can also change the value of an attribute using the DOM.</p>
<pre><code><span class="hljs-built_in">document</span>.getElementsByTag(“img”).src = “test.jpg”;
</code></pre><p>In this example we change the src of all _ t_ags to te_st.jpg.</p>
<h4 id="heading-changing-the-style">Changing the style</h4>
<p>To change the style of an HTML element we need to change the style property of our elements. Here is an example syntax for changing styles:</p>
<pre><code><span class="hljs-built_in">document</span>.getElementById(id).style.property = <span class="hljs-keyword">new</span> style
</code></pre><p>Now lets look at an example where we get an element and change the bottom border to a solid black line:</p>
<pre><code><span class="hljs-built_in">document</span>.getElementsByTag(“h1”).style.borderBottom = “solid <span class="hljs-number">3</span>px #<span class="hljs-number">000</span>”;
</code></pre><p>The CSS properties need to be written in camelcase instead of the normal css property name. In this example we used borderBottom instead of border-bottom.</p>
<h3 id="heading-adding-and-deleting-elements">Adding and deleting elements</h3>
<p>Now we will take a look at how we can add new elements and delete existing ones.</p>
<h4 id="heading-adding-elements">Adding elements</h4>
<pre><code><span class="hljs-keyword">var</span> div = <span class="hljs-built_in">document</span>.createElement(‘div’);
</code></pre><p>Here we just create a div element using the <em>createElement()</em> method which takes a tagname as a parameter and saves it into a variable. After that we just need to give it some content and then insert it into our DOM document.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> newContent = <span class="hljs-built_in">document</span>.createTextNode(<span class="hljs-string">"Hello World!"</span>); 
div.appendChild(newContent);
<span class="hljs-built_in">document</span>.body.insertBefore(div, currentDiv);
</code></pre>
<p>Here we create content using the createTextNode() method which takes a String as a parameter and then we insert our new div element before a div that already exists in our document.</p>
<h4 id="heading-deleting-elements">Deleting elements</h4>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> elem = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#header'</span>);
elem.parentNode.removeChild(elem);
</code></pre>
<p>Here we get an element and delete it using the removeChild() method.</p>
<h4 id="heading-replace-elements">Replace elements</h4>
<p>Now let’s take a look at how we can replace items.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> div = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#div'</span>);
<span class="hljs-keyword">var</span> newDiv = <span class="hljs-built_in">document</span>.createElement(‘div’);
newDiv.innerHTML = <span class="hljs-string">"Hello World2"</span>
div.parentNode.replaceChild(newDiv, div);
</code></pre>
<p>Here we replace an element using the <em>replaceChild()</em> method. The first argument is the new element and the second argument is the element which we want to replace.</p>
<h4 id="heading-writing-directly-into-the-html-output-stream">Writing directly into the HTML output stream</h4>
<p>We can also write HTML expressions and JavaScript directly into the HTML output stream using the write() method.</p>
<pre><code class="lang-js"><span class="hljs-built_in">document</span>.write(“&lt;h1&gt;Hello World!&lt;<span class="hljs-regexp">/h1&gt;&lt;p&gt;This is a paragraph!&lt;/</span>p&gt;”);
</code></pre>
<p>We can also pass JavaScript expressions like a date object.</p>
<pre><code><span class="hljs-built_in">document</span>.write(<span class="hljs-built_in">Date</span>());
</code></pre><p>The write() method can also take multiple arguments that will be appended to the document in order of their occurrence.</p>
<h3 id="heading-event-handlers">Event Handlers</h3>
<p>The HTML DOM also allows Javascript to react to HTML events. Here I’ve just listed some of the most important ones:</p>
<ul>
<li>mouse click</li>
<li>page load</li>
<li>mouse move</li>
<li>input field change</li>
</ul>
<h4 id="heading-assign-events">Assign Events</h4>
<p>You can define events directly in your HTML code using attributes on your tags. Here is an example of an <em>onclick</em> event:</p>
<pre><code>&lt;h1 onclick=”<span class="hljs-built_in">this</span>.innerHTML = ‘Hello!’”&gt;Click me!&lt;/h1&gt;
</code></pre><p>In this example, the text of the </p><h1 id="heading-will-change-to-hello-when-you-click-the-button-you-can-also-call-functions-when-an-event-is-triggered-as-you-can-see-in-the-next-example-click-me-here-we-call-the-changetext-method-when-the-button-is-clicked-and-pass-the-element-as-an-attribute-we-can-also-assign-the-same-events-in-our-javascript-code-documentgetelementbyidbtnonclick-changetext"> will change to “Hello!” when you click the button.<p></p>
<p>You can also call functions when an event is triggered as you can see in the next example.</p>
<pre><code>&lt;h1 onclick=”changeText(<span class="hljs-built_in">this</span>)”&gt;Click me!&lt;/h1&gt;
</code></pre><p>Here we call the <em>changeText()</em> method when the button is clicked and pass the element as an attribute.</p>
<p>We can also assign the same events in our Javascript code.</p>
<pre><code><span class="hljs-built_in">document</span>.getElementById(“btn”).onclick = changeText();
</code></pre></h1><h4 id="heading-assign-events-listeners">Assign Events Listeners</h4>
<p>Now let’s look at how you can assign event listeners to your HTML elements.</p>
<pre><code><span class="hljs-built_in">document</span>.getElementById(“btn”)addEventListener(<span class="hljs-string">'click'</span>, runEvent);
</code></pre><p>Here we just assigned a clickevent that calls the runEvent method when our btn element is clicked.</p>
<p>You can also assign multiple events to a single element:</p>
<pre><code><span class="hljs-built_in">document</span>.getElementById(“btn”)addEventListener(<span class="hljs-string">'mouseover'</span>, runEvent);
</code></pre><h3 id="heading-node-relationships">Node Relationships</h3>
<p>The nodes in the DOM Document have a hierarchical relationship to each other. This means that the nodes are structured like a tree. We use the terms parent, sibling and child to describe the relationship between nodes.</p>
<p>The top node is called the root and is the only node that has no parent. The root in a normal HTML document is the  tag because it has no parent and is the top tag of the document.</p>
<h4 id="heading-navigating-between-nodes">Navigating Between Nodes</h4>
<p>We can navigate between nodes using these properties:</p>
<ul>
<li>parentNode</li>
<li>childNodes</li>
<li>firstChild</li>
<li>lastChild</li>
<li>nextSibling</li>
</ul>
<p>Here is an example how you can get the parent element of an h1.</p>
<pre><code><span class="hljs-keyword">var</span> parent = <span class="hljs-built_in">document</span>.getElementById(“heading”).parentNode
</code></pre><h3 id="heading-conclusion">Conclusion</h3>
<p>You made it all the way until the end! Hope that this article helped you understand the Javascript DOM and how to use it to manipulate elements on your website.</p>
<p>If you want to read more articles just like this one you can visit my <a target="_blank" href="https://gabrieltanner.org/">website</a> or start following my <a target="_blank" href="https://gabrieltanner.us20.list-manage.com/subscribe/post?u=9d67fc028348a0eb71318768e&amp;id=6845ed3555">newsletter</a>.</p>
<p>If you have any questions or feedback, let me know in the comments down below.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
