Javascript
  • intro.
  • 1 - Getting started
  • 2 - Basics
  • 3 - Functions and Scope
  • 4 - Advanced Concepts
  • 5 - JavaScript in the Browser
  • 6 - JavaScript and Browser Storage
  • 7 - Asynchronous JavaScript
  • 8 - Design Patterns
  • 9 - Frameworks Overview
  • 10 - Testing and Debugging
Powered by GitBook
On this page
  • Introduction to the DOM (Document Object Model)
  • What is the DOM?
  • Tree Structure
  • Selecting Elements in the DOM
  • Common Methods for Selecting Elements
  • Modifying the DOM
  • DOM Events
  • What are Events?
  • Adding Event Listeners
  • Common Event Types
  • Traversing the DOM
  • Parent, Child, and Sibling Relationships
  • Creating and Removing Elements

5 - JavaScript in the Browser

Introduction to the DOM (Document Object Model)

What is the DOM?

  • DOM: A representation of the structure of a web page as a tree of objects.

    • Document: The entire HTML document.

    • Object Model: Each part of the HTML document (elements, attributes, text) is represented as an object.

  • Access and Manipulate: JavaScript can interact with the DOM to modify content, styles, and structure dynamically.

Tree Structure

  • HTML Tree: Represents the hierarchy of elements on the page.

    • Example Tree:

      <html>
        <body>
          <div>
            <h1>Title</h1>
            <p>Paragraph</p>
          </div>
        </body>
      </html>
    • Nodes: Elements like <div>, <h1>, and <p> are nodes in the tree.

    • Types of Nodes:

      • Element Nodes: Represent HTML elements (e.g., <div>).

      • Text Nodes: Contain text content inside elements.

      • Attribute Nodes: Represent attributes of HTML elements (e.g., id, class).

Selecting Elements in the DOM

Common Methods for Selecting Elements

  • getElementById(): Selects an element by its ID.

    • Example:

      const title = document.getElementById("main-title");
      console.log(title);  // Outputs the element with ID 'main-title'
  • getElementsByClassName(): Selects elements by their class name.

    • Example:

      const items = document.getElementsByClassName("item");
      console.log(items);  // Outputs an HTMLCollection of elements with class 'item'
  • getElementsByTagName(): Selects elements by their tag name.

    • Example:

      const paragraphs = document.getElementsByTagName("p");
      console.log(paragraphs);  // Outputs an HTMLCollection of all <p> elements
  • querySelector(): Selects the first element that matches a CSS selector.

    • Example:

      const header = document.querySelector(".header");
      console.log(header);  // Outputs the first element with class 'header'
  • querySelectorAll(): Selects all elements that match a CSS selector.

    • Example:

      const paragraphs = document.querySelectorAll("p");
      console.log(paragraphs);  // Outputs a NodeList of all <p> elements
    • Difference: getElementsByClassName() and getElementsByTagName() return live collections, whereas querySelectorAll() returns a static NodeList.

Modifying the DOM

Changing Content

  • textContent and innerHTML: Modify the text or HTML content of an element.

    • textContent: Changes only the text inside an element, safer against XSS.

    • innerHTML: Allows you to insert HTML, but may expose to security risks if not handled properly.

    • Example:

      const title = document.getElementById("main-title");
      title.textContent = "New Title";  // Changes the text content of the title
      title.innerHTML = "<span>Updated Title</span>";  // Replaces HTML within the title
    • Using outerHTML: Replaces the entire element, including the element itself.

      title.outerHTML = "<h2>Replaced Title</h2>";

Changing Attributes

  • setAttribute() and getAttribute(): Modify or get the attributes of an element.

    • Example:

      const link = document.querySelector("a");
      link.setAttribute("href", "https://www.example.com");
      console.log(link.getAttribute("href"));  // Outputs: "https://www.example.com"
  • Direct Property Access: You can also modify attributes using direct property access.

    • Example:

      link.href = "https://www.another-example.com";
      console.log(link.href);  // Outputs: "https://www.another-example.com"

Changing Styles

  • Inline Styles: Modify CSS styles directly using the style property.

    • Example:

      const box = document.querySelector(".box");
      box.style.backgroundColor = "blue";
      box.style.width = "200px";
  • Adding and Removing Classes: Use classList to manipulate CSS classes.

    • Methods:

      • add(): Adds a new class.

      • remove(): Removes a class.

      • toggle(): Adds or removes a class depending on whether it is present.

      • contains(): Checks if an element contains a specified class.

    • Example:

      const button = document.querySelector("button");
      button.classList.add("active");
      button.classList.remove("inactive");
      button.classList.toggle("highlight");  // Adds or removes the class 'highlight'
      console.log(button.classList.contains("active"));  // true or false

DOM Events

What are Events?

  • Events: Actions that occur in the browser, such as clicks, key presses, or mouse movements.

    • JavaScript can react to these events by executing functions known as event handlers.

Adding Event Listeners

  • addEventListener(): Attaches a function to run when a specific event occurs.

    • Syntax:

      element.addEventListener(event, function, useCapture);
    • Example:

      const button = document.querySelector("button");
      button.addEventListener("click", function() {
          alert("Button clicked!");
      });
    • Arrow Function as Event Listener:

      button.addEventListener("click", () => {
          console.log("Button clicked with arrow function");
      });
    • Removing Event Listeners: You can use removeEventListener() to remove a previously added listener.

      function handleClick() {
          console.log("Button clicked!");
      }
      button.addEventListener("click", handleClick);
      button.removeEventListener("click", handleClick);  // Removes the click event listener

Common Event Types

  • Mouse Events: click, dblclick, mousedown, mouseup, mouseover, mouseout

  • Keyboard Events: keydown, keyup, keypress

    • Example: Handling keyboard input

      document.addEventListener("keydown", function(event) {
          console.log("Key pressed: " + event.key);
      });
  • Form Events: submit, change, input, focus, blur

    • Example of a form event:

      const form = document.querySelector("form");
      form.addEventListener("submit", function(event) {
          event.preventDefault();  // Prevents the default form submission
          console.log("Form submitted");
      });

Traversing the DOM

Parent, Child, and Sibling Relationships

  • Parent Node: The element directly above a given element in the DOM tree.

    • Example:

      const item = document.querySelector(".item");
      console.log(item.parentNode);  // Outputs the parent element of the item
  • Child Nodes: The elements directly inside a given element.

    • children vs childNodes:

      • children: Returns an HTMLCollection of only the element nodes.

      • childNodes: Returns all child nodes, including text and comment nodes.

    • Example:

      const list = document.querySelector("ul");
      console.log(list.children);  // Outputs an HTMLCollection of <li> children
      console.log(list.childNodes);  // Outputs all types of child nodes
  • Sibling Nodes: Elements that share the same parent.

    • Example:

      const firstItem = document.querySelector(".item");
      console.log(firstItem.nextElementSibling);  // Outputs the next sibling element
      console.log(firstItem.previousElementSibling);  // Outputs the previous sibling element

Creating and Removing Elements

Creating Elements

  • document.createElement(): Creates a new element that can be added to the DOM.

    • Adding Attributes and Content:

      const newDiv = document.createElement("div");
      newDiv.textContent = "Hello, I am a new div!";
      newDiv.setAttribute("class", "new-div");
      document.body.appendChild(newDiv);  // Adds the new div to the end of the <body>
  • Inserting Elements at Specific Positions:

    • insertBefore(): Inserts a new node before a specified existing node.

      const list = document.querySelector("ul");
      const newItem = document.createElement("li");
      newItem.textContent = "New Item";
      list.insertBefore(newItem, list.firstChild);  // Adds the new item as the first child of the list

Removing Elements

  • removeChild(): Removes a child element from its parent.

    • Example:

      const list = document.querySelector("ul");
      const listItem = document.querySelector("li");
      list.removeChild(listItem);  // Removes the selected list item from the list
  • remove(): Directly removes an element from the DOM.

    • Example:

      const box = document.querySelector(".box");
      box.remove();  // Removes the box element
  • Clearing All Children: Removing all child nodes of an element.

    • Example:

      const container = document.querySelector(".container");
      while (container.firstChild) {
          container.removeChild(container.firstChild);
      }

Summary

  • DOM: The Document Object Model represents the structure of a web page, allowing JavaScript to dynamically interact with HTML elements.

  • Selecting Elements: Use methods like getElementById(), querySelector(), and others to access elements.

  • Modifying Elements: Change content, attributes, and styles using properties like textContent, setAttribute(), and classList.

  • Events: Attach event listeners to handle user interactions, such as mouse clicks and keyboard presses.

  • Traversing and Manipulating the DOM: Understand parent, child, and sibling relationships, and learn how to create and remove elements dynamically.

  • Event Handling: Manage user input and interactions effectively using addEventListener() and related methods.


Next Chapter: JavaScript and Browser Storage

Previous4 - Advanced ConceptsNext6 - JavaScript and Browser Storage

Last updated 6 months ago