DOM Manipulation

Learning Goals

  • Review what the DOM is
  • Explain what CRUD actions are
  • Observe how to do CRUD actions on the DOM
  • Explain how the DOM is able to read code written in JS files

Single Page Applications

  • JavaScript renders the content of the page dynamically

  • Avoids page refreshes

  • Page transitions are much faster

Mapquest image

https://techcrunch.com/wp-content/uploads/2007/10/picture-242.png

Document
Object
Model

The DOM as a Tree

MDN: Element - MDN: Node

Tasks

  • Select single DOM elements with:
    • .querySelector()
    • or.getElementById()
  • Select multiple elements with:
    • .querySelectorAll()
    • or .getElementsByClassName()
  • Add content with .textContent= or .innerText=
  • Create elements with .createElement()
  • Append elements to the DOM with .appendChild() and .append()
  • Explain the dangers of innerHTML=
  • Remove content with .remove()
  • Visit TVMaze to practice

Features

  • renderHeader(): renders the header content via JS
  • renderFooter(): renders the footer content via JS
  • renderBook(): create a list item for a book and inserts it into the list
  • NEXT LECTURE: removeBook(index): removes a book li from the DOM by its index in the ul

The Dangers of innerHTML=

Bread and Butter tools

  • Create
    • document.createElement()
  • Read
    • querySelector() & querySelectorAll()
  • Update
    • textContent =
    • append()
    • classList for adding and removing classes from an element
    • dot notation for editing properties (eg. img.src = imageUrl, or div.className = "card")
  • Destroy
    • remove()

Links!