The DOM (Document Object Model)

Learning Objectives

Framing (5 min)

The Document Object Model is a programming interface for HTML.

An HTML document is available for us to manipulate as an object, and this object is structured like a tree:

DOM diagram
DOM diagram

Or this:

html
└── head
│   ├──title
│   ├──meta
│   ├──link[rel="stylesheet"]
|   └──script[type="text/javascript"]
|
└── body
    ├── header
    │   ├── h1
    │   └── nav
    └── section.simplicity
    |   └── h2
    │   └── article
    ├── section.life
    |   └── h2
    │   └── article
    │       └── block_quote
    │       └── block_quote
    └── footer

Traversing the DOM

You Do: Explore the DOM

  1. Go to the deployed version of the Tic Tac Toe exercise.
  2. Open the Chrome console (Command + Option + J)
  3. Use jQuery to select the square with the class of "board"
  4. Save the board to a variable
  5. console.dir the variable
  6. Use your mouse to expand the 0 property of the variable. This is the DOM object representation of the game board's element

To access the element with "vanilla" JS, you would use document.querySelector(".board")

Answer:

Bonus

You Do: JS DOM Quotes, Part 1: Selector review

Checkout the jquery branch.

Link

You Do: JS DOM Quotes, Part 2: DOM Traversal

Checkout the jquery branch.

Link

Manipulating the DOM

You do: Hijack a webpage

Here's an artist's interpretation of true beauty:

Mona

It's rather inadequate. Go to Nicholas Cage's Wikipedia page and copy the URL of your favorite image on the page. Then, use your browser's console and jQuery to replace the image above with the image of Nic Cage.

You do: Cheat with Javascript

Go to CookieClicker. Click the cookie a few times.

Ain't nobody got time for this.

  1. Save the cookie element to a variable.
  2. Use Javascript to simulate a click on the cookie.
  3. Use a timing function to make Javascript click the cookie once every millisecond.
  4. Now bookmark CookieClicker to save it for later, close the page, and pay attention in class.

Building Math Minute

Watch this series of videos on making Math Minute

Play with it here

Here's the Repo

References