JavaScript DOM Documents

The Document Object Model (DOM) is a vital component of web development, providing a structured representation of web pages and enabling dynamic interaction and manipulation through JavaScript.

The DOM document forms the root of this hierarchical structure, offering a gateway to access and control various elements and properties within the HTML or XML document.

What is the DOM Document?

The DOM document is the root node of the DOM tree, representing the entire HTML or XML document.

It serves as an entry point for accessing and manipulating the elements and content of the web page.

The document object in JavaScript provides various properties and methods to interact with the DOM.

// Accessing the DOM document
console.log(document.title); // Outputs the title of the document       
console.log(document.URL); // Outputs the URL of the document       

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>
          console.log(document.title); // Outputs the title of the document       
          console.log(document.URL); // Outputs the URL of the document       
        </script>
      </body>
  </html>

Accessing Elements

Accessing elements is a fundamental operation in DOM manipulation.

The document object provides several methods to select elements, including getElementById(), getElementsByClassName(), getElementsByTagName(), querySelector() and querySelectorAll().

// Accessing 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 Inserting Elements

Creating and inserting new elements into the DOM allows for dynamic content updates.

The document.createElement()method is used to create new elements, which can then be inserted into the DOM using methods like appendChild()and insertBefore().

// Creating and inserting elements
const newItem = document.createElement("li");
newItem.textContent = "New Item";
document.body.appendChild(newItem);

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

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 is achieved using methods like removeChild()or remove().

These methods allow for the deletion of specific elements, which can be selected and then removed from their parent node.

// Removing an element
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>

Modifying Element Attributes

The documentobject provides methods to modify the attributes of DOM elements dynamically.

The setAttribute(), getAttribute(), and removeAttribute()allow for the addition, retrieval, and removal of attributes on elements.

// Modifying element 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>

Event Handling

Handling events is a crucial aspect of interactive web applications.

The document object allows for the registration of event listeners that respond to user interactions such as clicks, keypresses, and mouse movements.

Methods like addEventListener() are used to attach event handlers to elements.

// Event Handling
const button = document.getElementById("myButton");

button.addEventListener("click", () => {
  console.log("Button clicked!"); 
})

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");

          button.addEventListener("click", () => {
            console.log("Button clicked!"); 
          })
        </script>
      </body>
  </html>

Document Properties and Methods

The document object provides numerous properties and methods to interact with the document.

Properties like document.title, document.URL, and document.bodygive information about the document, while methods like document.write()and document.close() allow for direct manipulation of the document content.

// Document properties and methods
console.log(document.title); // Outputs the title of the document       
document.title = "New Title" // Changes the title of the document

console.log(document.URL); // Outputs the URL of the document       
document.write("Hello, world!"); // Writes directly to the document       

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>
      console.log(document.title); // Outputs: the title of the document       
      document.title = "New Title" // Changes the title of the document
      console.log(document.title); // Outputs: New title      

      console.log(document.URL); // Outputs: the URL of the document       
      document.write("Hello, world!"); // Writes directly to the document       
    </script>
  </body>
</html>

The DOM document in JavaScript is the foundation for web page interaction and manipulation.

From selecting and creating elements to handling events and modifying attributes, mastering the DOM document is essential for effective web development.

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