JavaScript DOM Methods

The Document Object Model (DOM) is a crucial part of web development, representing the structure of web pages in a tree-like format that can be manipulated with JavaScript.

DOM methods are essential tools for interacting and modifying web documents dynamically.

In this chapter, delves into various DOM methods, explaining their uses and providing code examples to demonstrate their functionality.

Selecting Elements

Selecting elements in DOM is one of the first step in interacting with the webpage.

JavaScript provides several methods for selecting elements, each with specific use cases:

  • getElementById():Selects an element by its ID.
  • getElementsByClassName():Selects all elements with a given class name.
  • getElementsByTagName():Selects all elements with a given tag name.
  • querySelector():Selects the first element that matches a CSS selector.
  • querySelectorAll():Selects all elements that match a CSS selector.
// Selecting elements
const heading = document.getElementById("heading");
const items = document.getElementsByClassName("item");
const paragraphs = document.getElementsByTagName("p");
const firstItem = document.querySelector(".item");
const allItems = document.querySelectorAll(".item");

console.log(heading); // Logs the element with ID 'header'         
console.log(items); // Logs an HTMLCollection of elements with class 'item'         
console.log(paragraphs); // Logs an HTMLCollection of <p> elements          
console.log(firstItem); // Logs the first element with class 'item'         
console.log(allItems); // Logs a NodeList of elements with class 'item'      

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <p id="item">this is first paragraph</p>
        <p id="item">this is second paragraph</p>
        <p id="item">this is third paragraph</p>
        <script>
          const heading = document.getElementById("heading");
          const items = document.getElementsByClassName("item");
          const paragraphs = document.getElementsByTagName("p");
          const firstItem = document.querySelector(".item");
          const allItems = document.querySelectorAll(".item");
          
          console.log(heading); // Logs the element with ID 'header'         
          console.log(items); // Logs an HTMLCollection of elements with class 'item'         
          console.log(paragraphs); // Logs an HTMLCollection of <p> elements          
          console.log(firstItem); // Logs the first element with class 'item'         
          console.log(allItems); // Logs a NodeList of elementspth clapitem'      
        </script>
      </body>
  </html>

Creating Elements

Creating new elements is a common task when dynamically updating the DOM.

The createElement()method allows you to create new HTML elements, which can then be appended to the DOM.

// Creating a new element
const newDiv = document.createElement("div");

newDiv.textContent = "Hello, World!";

document.body.appendChild(newDiv);

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <script>
          const newDiv = document.createElement("div");

          newDiv.textContent = "Hello, World!";

          document.body.appendChild(newDiv);
          console.log(newDiv);      
        </script>
      </body>
  </html>

Appending and Inserting Elements

Once an element is created, it needs to be inserted into the DOM.

The appendChild()method adds an element as the last child of a parent element, while insertBefore()can insert an element before a specified child.

// Appending and inserting elements
const newItem = document.createElement("li");
newItem.textContent = "New Item";
const list = document.getElementById("myList");
list.appendChild(newItem);

const anotherItem = document.createElement("li");
anotherItem.textContent = "Another Item";
const list = document.getElementById("myList");
list.insertBefore(anotherItem, list.firstChild);

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <ul id="myList">
          <li>Banana</li>
        </ul>
        <script>
        const newItem = document.createElement("li");
          newItem.textContent = "New Item";
          const list = document.getElementById("myList");
          list.appendChild(newItem);

          const anotherItem = document.createElement("li");
          anotherItem.textContent = "Another Item";
          const anotherList = document.getElementById("myList");
          anotherList.insertBefore(anotherItem, list.firstChild);
          const listItems = document.querySelectorAll("li");

          listItems.forEach(item => { 
            console.log(item.textContent);
          })
        </script>
      </body>
  </html>

Removing Elements

Removing elements from the DOM can be done using the removeChild()method.

First, you need to select the parent element and then remove the specific child element.

// Removing an element
const itemToRemove = document.getElementById("itemToRemove");
itemToRemove.parentNode.removeChild(itemToRemove);

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <h4 id="itemToRemove">This content will be available</h4>
        
        <script>
        const itemToRemove = document.getElementById("itemToRemove");
          itemToRemove.parentNode.removeChild(itemToRemove);
        </script>
      </body>
  </html>

Replacing Elements

The replaceChild()method allows you to replace an existing child element with a new one.

This is useful when you need to update content or change the structure of the DOM dynamically.

// Replacing an element
const newParagraph = document.createElement("p");
newParagraph.textContent = "This is the new paragraph.";
const oldParagraph = document.getElementById("oldParagraph");
oldParagraph.parentNode.replaceChild(newParagraph, oldParagraph);

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <p id="oldParagraph">This is old paragraph and it will be replace</p>
        
        <script>
          const newParagraph = document.createElement("p");
          newParagraph.textContent = "This is the new paragraph.";
          const oldParagraph = document.getElementById("oldParagraph");
          oldParagraph.parentNode.replaceChild(newParagraph, oldParagraph);
        </script>
      </body>
  </html>

Cloning Elements

Cloning elements can be useful when you need to duplicate a node.

The cloneNode()method creates a copy of the specified node.

If you pass trueas an argument, it will perform a deep clone, copying all descendants as well.

// Cloning an element
const originalItem = document.getElementById("originalItem");
const clone = originalItem.cloneNode(true);
document.body.appendChild(clone);

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <p id="originalItem">This is cloning an Element</p>
        
        <script>
          const originalItem = document.getElementById("originalItem");
          const clone = originalItem.cloneNode(true);
          document.body.appendChild(clone);
        </script>
      </body>
  </html>

Modifying Attributes

DOM methods also include capabilities for modifying element attributes.

The setAttribute(), getAttribute(), and removeAttribute()methods allow you to manage attributes of DOM elements dynamically.

// Modifying attributes
const link = document.querySelector("a");
link.setAttribute("href", "https://www.example.com");
console.log(link.getAttribute("href")); // Output: 'https://www.example.com'
link.removeAttribute("href");

Example

<!DOCTYPE HTML>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Title of the Document</title>
      </head>
      <body>
        <h1 id="heading">Welcome to CodingKoleji</h1>
        <a>Visit my website</a>
        
        <script>
          const link = document.querySelector("a");
          link.setAttribute("href", "https://codingkoleji.com");
          console.log(link.getAttribute("href")); // Output: 'https://www.example.com'
          link.removeAttribute("href");
        </script>
      </body>
  </html>

DOM methods in JavaScript provide powerful tools for interacting with and manipulating the structure and content of web pages.

By mastering these methods, you can be able to can create dynamic, responsive, and interactive web applications.

Techniques such as batch updates, using document fragments, and minimizing reflows and repaints can help improve DOM performance.

From selecting and creating elements to appending, removing, and modifying them, DOM methods are essential for modern web development.

Let's learn about DOM documents in the next chapter.