JavaScript DOM Elements

The Document Object Model (DOM) is the backbone of web development, representing the structure of web pages as a tree of objects.

DOM elements are the building blocks of this structure, encapsulating the HTML elements and their properties, attributes, and behaviors.

Accessing DOM Elements

Accessing DOM elements is the first step in any DOM manipulation. JavaScript provides several methods to select elements from the DOM.

These include document object provides several methods to select elements, including getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector() and querySelectorAll(), each serving different use cases.

// Accessing DOM 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 and Appending DOM Elements

Creating new DOM elements dynamically allows for real-time updates to web pages.

The document.createElement()method is used to create a new element, which can then be appended to an existing element using appendChild().

// Creating and appending DOM elements
const newList = document.createElement("li");
newList.textContent = "New Item";
document.body.appendChild(newList);

const newItem = document.createElement("li");
newItem.textContent = "New Item";
const list = document.getElementById("myList");
list.appendChild(newItem);

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 newList = document.createElement("li");
      newList.textContent = "New Item";
      document.body.appendChild(newList);
      
      const newItem = document.createElement("li");
      newItem.textContent = "New Item";
      const list = document.getElementById("myList");
      list.appendChild(newItem);
    </script>
  </body>
</html>

Modifying DOM Elements

Once elements are selected, they can be modified using various properties and methods.

You can change the content, style, and attributes of elements dynamically.

Properties like textContent, innerHTMLand styleare commonly used for these purposes.

// Modifying DOM elements
const header = document.getElementById("header");
header.textContent = "Updated Header";

const paragraph = document.querySelector("p");
paragraph.innerHTML = "<strong>Bold text</strong>";

const button = document.querySelector("button");
button.style.backgroundColor = "blue";
button.style.color = "white";

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>this is a paragraph</p>
    <button>Submit</button>
    
    <script>
      const heading = document.getElementById("heading");
      heading.textContent = "Hello from the Founder of CodingKoleji";
      
      const paragraph = document.querySelector("p");
      paragraph.innerHTML = "<strong>Bold text</strong>";
      
      const button = document.querySelector("button");
      button.style.backgroundColor = "blue";
      button.style.color = "white";
    </script>
  </body>
</html>

Removing DOM Elements

Removing elements from the DOM is essential for cleaning up and managing the document structure.

The removeChild()method removes a child element from its parent, while remove()can directly remove an element.

// Removing DOM elements
const itemToRemove = document.getElementById("itemToRemove");
itemToRemove.parentNode.removeChild(itemToRemove);

// Alternative method using remove()
const anotherItemToRemove  = document.querySelector(".removeMe");
anotherItemToRemove.remove();

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 paragraph will be remove</h4>
        <h4 id="removeMe">This paragraph this also will be remove</h4>
        
        <script>
          const itemToRemove = document.getElementById("itemToRemove");
          itemToRemove.parentNode.removeChild(itemToRemove);

          // Alternative method using remove()
          const anotherItemToRemove  = document.querySelector(".removeMe");
          anotherItemToRemove.remove();
        </script>
      </body>
  </html>

Handling Attributes of DOM Elements

Attributes of DOM elements can be accessed and modified using methods like setAttribute(), getAttribute(), and removeAttribute().

This allows for dynamic manipulation of element properties.

// Handling attributes of DOM elements
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>

Event Handling on DOM Elements

Event handling is crucial for creating interactive web pages.

The addEventListener() method allows you to attach event listeners to DOM elements, enabling them to respond to user actions such as clicks, key presses, and mouse movements.

// Event handling on DOM elements
const button = document.getElementById("myButton");

button.addEventListener("click", () => {
  console.log("Button clicked!");
  const heading = document.querySelector(".heading");
  heading.style.backgroundColor = "blue";
  heading.style.color = "white";
})

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>
    <button id="myButton">Click Me!</button>
    <script>
      const button = document.getElementById("myButton");
      const heading = document.querySelector(".heading");

      button.addEventListener("click", () => {
        console.log("Button clicked!"); 
        heading.style.backgroundColor = "blue";
        heading.style.color = "white";
      })
    </script>
  </body>
</html>

Cloning DOM Elements

Cloning DOM elements is useful when you need to duplicate elements.

The cloneNode()method creates a copy of the element.

Passing trueas an argument performs a deep clone, copying all child elements as well.

// Cloning DOM elements
const originalItem = document.getElementById("originalItem");
const clone = parentNode.originalItem(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>

Traversing DOM Elements

Traversal methods allow you to navigate through the DOM tree to find elements relative to others.

Methods like parentNode, childNodes, firstChild, lastChild, nextSibling, and previousSiblingfacilitate this process.

// Traversing DOM elements
const listItem = document.querySelector("li");
console.log(listItem.parentNode); // Logs the parent node of the <li> element      
console.log(listItem.childNodes); // Logs the child nodes of the <li> element      
console.log(listItem.nextSibling); // Logs the next sibling of the <li> element      

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>
      <li>Apple</li>
      <li>Orange</li>
    </ul>
    <script>
      const listItem = document.querySelector("li");
      console.log(listItem.parentNode); // Logs the parent node of the <li> element      
      console.log(listItem.childNodes); // Logs the child nodes of the <li> element      
      console.log(listItem.nextSibling); // Logs the next sibling of the <li> element      
    </script>
  </body>
</html>

DOM elements are the fundamental units of web pages, and understanding how to interact with them using JavaScript is essential for modern web development.

This knowledge is a cornerstone for building responsive and engaging user experiences on the web.

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