What is the DOM?
When a browser loads HTML, it builds a tree of objects called the DOM. JavaScript can use those objects to update the page without reloading it.
document
└── body
├── h1
└── button
In the examples below, the HTML creates the page elements and script.js uses the DOM to interact with them.
1. Find an element and change it
getElementById() finds one element by its unique id. The textContent property reads or replaces its text.
This text will change when you click the button.
2. Listen for an event
An event is something that happens on the page, such as a click. addEventListener() runs a function when that event occurs.
3. Read input from a form
The value property contains what a user typed into an input field.
Your greeting will appear here.
4. Create and remove elements
createElement() makes a new element, and appendChild() adds it to the page. Each item also gets a button that removes it.
DOM methods in this lesson
document.getElementById()selects by id.document.querySelector()selects the first matching CSS selector.addEventListener()responds to events.textContentchanges text;classList.toggle()switches a CSS class.createElement()andappendChild()add new elements.remove()removes an element from the page.