Week 7

Nov 1, 2024

WEB222 - Week 7

From HTML to the DOM

  • HTML provides initial structure for web pages.
  • Browsers parse HTML into a modifiable DOM Tree.
  • DOM Tree: A living version of HTML consisting of nodes.
    • Types of Nodes: Elements, Text Nodes, Attribute Nodes.
  • DOM Tree structure is crucial for web page rendering.
  • Developer tools in browsers allow interaction with the DOM.

Programming the DOM

  • DOM: Document Object Model, an interface for scripts to modify documents.
  • JavaScript utilizes DOM to make web pages dynamic.

DOM Access in JavaScript

  • Accessed via window.document.
    let document = window.document;
    
  • Methods to find elements:
    • document.getElementById(id)
    • document.querySelector(selectors)
    • document.querySelectorAll(selectors)

Modifying the DOM

  • Create elements:
    • document.createElement(name)
    • document.createTextNode(text)
  • Insert elements:
    • .appendChild()
    • .insertBefore(new, old)
  • Remove elements:
    • .removeChild()

Inspecting and Modifying Elements

  • Element Properties:
    • element.id, element.innerHTML, element.parentNode
  • Element Methods:
    • .querySelector(), .querySelectorAll(), .scrollIntoView()

Events in the DOM

  • Event-Driven Programming: Functions execute in response to events.
  • Registering Event Handlers:
    • element.onevent = function(e) {...}
    • element.addEventListener('event', function(e) {...})
  • Common Events: load, click, keypress, change.

The Event Object

  • Contains info about the event.
  • Useful methods:
    • e.preventDefault(), e.stopPropagation()

Timers

  • Delays using:
    • setTimeout(function, delayMS)
    • setInterval(function, delayMS)

DOM Programming Exercise

  • Create and modify HTML pages using JavaScript:
    • Load images and text dynamically.
    • Handle user interactions and events.
    • Use timers and event handlers to create interactive web experiences.