Instagram
youtube
Facebook
Twitter

The DOM (Document Object Model)

In this lesson, we will explore the Document Object Model (DOM), a crucial concept in web development that allows JavaScript to interact with HTML and CSS. The DOM represents the structure of a web page as a tree of objects, enabling developers to manipulate content, structure, and styles dynamically.


1. What is the DOM?

The DOM is a programming interface provided by browsers that represents the structure of a web document. It treats the HTML document as a tree of objects, where each element, attribute, and piece of text is represented as a node. This allows JavaScript to access and modify the document structure, style, and content.

1.1 Key Concepts

  • Nodes: The building blocks of the DOM, which include elements (like <div>, <p>, <a>), attributes, and text.
  • Elements: The individual HTML tags, which can have properties and methods.
  • Tree Structure: The hierarchical arrangement of nodes, with a single root node representing the entire document.

2. Accessing the DOM

JavaScript provides several methods to access and manipulate the DOM. The most commonly used methods are available through the document object.

2.1 Selecting Elements

You can select DOM elements using various methods:

  1. getElementById: Selects an element by its unique ID.

    let element = document.getElementById("myElement");
    
  2. getElementsByClassName: Selects elements by their class name (returns a live HTMLCollection).

    let elements = document.getElementsByClassName("myClass");
    
  3. getElementsByTagName: Selects elements by their tag name (returns a live HTMLCollection).

    let elements = document.getElementsByTagName("p");
    
  4. querySelector: Selects the first element that matches a CSS selector.

    let element = document.querySelector(".myClass");
    
  5. querySelectorAll: Selects all elements that match a CSS selector (returns a static NodeList).

    let elements = document.querySelectorAll("div.myClass");
    

3. Modifying the DOM

Once you have selected elements, you can modify their properties, attributes, and styles.

3.1 Changing Content

To change the inner content of an element, you can use the innerHTML or textContent properties.

Example

let element = document.getElementById("myElement");
element.innerHTML = "<strong>New Content</strong>"; // Sets HTML content
element.textContent = "New Plain Text"; // Sets plain text content

3.2 Changing Attributes

You can change an element's attributes using the setAttribute method or by directly modifying the property.

Example

let link = document.querySelector("a");
link.setAttribute("href", "https://www.example.com"); // Using setAttribute
link.href = "https://www.newsite.com"; // Directly modifying property

3.3 Changing Styles

You can modify the CSS styles of an element using the style property.

Example

let element = document.getElementById("myElement");
element.style.color = "red"; // Change text color
element.style.backgroundColor = "yellow"; // Change background color

4. Creating and Removing Elements

You can also create new elements and remove existing ones using the DOM methods.

4.1 Creating Elements

To create a new element, use document.createElement() and append it to the desired parent element.

Example

let newElement = document.createElement("div");
newElement.textContent = "I am a new element!";
document.body.appendChild(newElement); // Append to the body

4.2 Removing Elements

To remove an element, you can use the removeChild() method on its parent or the remove() method on the element itself.

Example

let elementToRemove = document.getElementById("removeMe");
elementToRemove.parentNode.removeChild(elementToRemove); // Remove using parent
// OR
elementToRemove.remove(); // Directly remove the element

5. Handling Events

Events are actions or occurrences that happen in the browser, such as clicks, key presses, or mouse movements. JavaScript can respond to these events using event listeners.

5.1 Adding Event Listeners

You can add event listeners to elements using the addEventListener method.

Example

let button = document.getElementById("myButton");
button.addEventListener("click", function() {
    alert("Button clicked!");
});

5.2 Removing Event Listeners

You can remove event listeners using the removeEventListener method. However, you need to pass the same function reference used when adding the listener.

Example

function handleClick() {
    alert("Button clicked!");
}

button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick); // Remove the listener

6. Practical Exercises

Create a JavaScript file named domManipulation.js and complete the following exercises:

  1. Change the Background Color: Write a function that changes the background color of a specified element when a button is clicked.

  2. Create a List: Create a function that generates a list of items from an array and appends it to the DOM.

  3. Event Handling: Write a function that adds an event listener to a button. When the button is clicked, it should display a message in a specified element.

Example Solutions:

// 1. Change the Background Color
function changeBackgroundColor() {
    let element = document.getElementById("colorBox");
    element.style.backgroundColor = "lightblue";
}

document.getElementById("colorButton").addEventListener("click", changeBackgroundColor);

// 2. Create a List
function createList() {
    let items = ["Apple", "Banana", "Cherry"];
    let ul = document.createElement("ul");

    items.forEach(item => {
        let li = document.createElement("li");
        li.textContent = item;
        ul.appendChild(li);
    });

    document.body.appendChild(ul);
}

createList(); // Call the function to create and append the list

// 3. Event Handling
function showMessage() {
    let messageElement = document.getElementById("message");
    messageElement.textContent = "Button was clicked!";
}

document.getElementById("messageButton").addEventListener("click", showMessage);

Conclusion

In this lesson, we explored the Document Object Model (DOM) and learned how to access, modify, create, and remove elements in a web document. We also covered event handling, which allows us to respond to user interactions dynamically. Understanding the DOM is essential for building interactive and engaging web applications.

In the next lesson, we will discuss Event Handling, where we will delve deeper into handling various events and event propagation in JavaScript.