DOM Manipulation1/17

What is the DOM?

The DOM: Your Page as Objects ๐ŸŒณ

The DOM (Document Object Model) is how JavaScript sees and interacts with HTML. It turns your HTML into objects that JavaScript can manipulate!

Why is the DOM Important?

Without the DOM, JavaScript couldn't:

  • Change text on a page
  • Add/remove elements
  • Respond to clicks
  • Create interactive websites!

HTML โ†’ DOM Tree

Your HTML becomes a tree structure:

<html>
  <body>
    <h1>Hello</h1>
    <p>World</p>
  </body>
</html>

JavaScript sees this as:

document โ””โ”€โ”€ html โ””โ”€โ”€ body โ”œโ”€โ”€ h1 ("Hello") โ””โ”€โ”€ p ("World")

Every HTML element becomes a node in this tree.

The document Object

document is your gateway to the entire page:

// Page information
console.log(document.title);       // "My Page"
console.log(document.URL);         // "https://..."

// Access elements
console.log(document.body);        // The <body> element
console.log(document.head);        // The <head> element

What Can You Do with the DOM?

ActionExample
Read contentelement.textContent
Change contentelement.textContent = "New"
Add elementsparent.appendChild(child)
Remove elementselement.remove()
Change styleselement.style.color = "red"
Handle eventselement.addEventListener("click", ...)

Your Turn!

Access the document's title and store it in a variable.