JavaScript lesson · 20 min
JavaScript DOM Basics
Understand what the DOM is and how JavaScript can read elements from a page.
What you will practice
- Understand the DOM as a tree of page elements.
- Create simple HTML in a sandboxed page.
- Read text from elements with JavaScript.
What this means
DOM means Document Object Model. It is the browser's structured representation of an HTML page.
When the browser loads HTML, it turns tags like `h1`, `p`, `button`, and `form` into objects JavaScript can read and change.
This is the bridge between JavaScript as a language and JavaScript as something that can make a real web page interactive.
If this is your first time seeing this
The DOM is the live page structure the browser creates from HTML.
When JavaScript uses `document`, it is talking to the current page.
Mini glossary
- DOM
- The browser's object version of the HTML page.
- document
- The main JavaScript object used to read and change the page.
- textContent
- The plain text inside an element.
Example from everyday life
Think of the DOM as a stage where HTML elements are actors. The HTML file says which actors are on stage, and JavaScript can read their name tags, move them, change their lines, or ask them to react.
How it works step by step
- The example puts a small HTML layout into `document.body.innerHTML`.
- `document.querySelector("h1")` asks the DOM for the first heading element.
- `document.querySelector(".intro")` asks for the first element with the class `intro`.
- `textContent` reads the visible text stored inside each element.
Where you will use this
- A dashboard reads a heading before changing the current section title.
- A search page reads text from an input field before filtering results.
- A learning app finds a lesson title and updates progress beside it.
Before you run the code
The DOM is not the same as the HTML text you write in a file. It is the live page structure the browser builds from that HTML.
Once an element is in the DOM, JavaScript can read it, edit it, attach events to it, or remove it.
Common beginner mistakes
- Thinking the DOM is just a string of HTML. It is a live tree of objects.
- Trying to read an element before it exists on the page.
- Using `innerHTML` for user text when `textContent` would be safer.
Run the code to see console output here.
Code runs locally in an isolated sandboxed browser frame with a timeout. It is not sent to Lumio analytics or executed on the server.
Try changing this next
- Change the heading text and run the code.
- Add another paragraph and read it with a new selector.
- Try selecting `main` and printing its text.