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:

  • getElementsByClassName(): Selects elements by their class name.

    • Example:

  • getElementsByTagName(): Selects elements by their tag name.

    • Example:

  • querySelector(): Selects the first element that matches a CSS selector.

    • Example:

  • querySelectorAll(): Selects all elements that match a CSS selector.

    • Example:

    • 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:

    • Using outerHTML: Replaces the entire element, including the element itself.

Changing Attributes

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

    • Example:

  • Direct Property Access: You can also modify attributes using direct property access.

    • Example:

Changing Styles

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

    • Example:

  • 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:

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:

    • Example:

    • Arrow Function as Event Listener:

    • Removing Event Listeners: You can use removeEventListener() to remove a previously added listener.

Common Event Types

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

  • Keyboard Events: keydown, keyup, keypress

    • Example: Handling keyboard input

  • Form Events: submit, change, input, focus, blur

    • Example of a form event:

Traversing the DOM

Parent, Child, and Sibling Relationships

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

    • Example:

  • 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:

  • Sibling Nodes: Elements that share the same parent.

    • Example:

Creating and Removing Elements

Creating Elements

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

    • Adding Attributes and Content:

  • Inserting Elements at Specific Positions:

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

Removing Elements

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

    • Example:

  • remove(): Directly removes an element from the DOM.

    • Example:

  • Clearing All Children: Removing all child nodes of an element.

    • Example:

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

Last updated