The DOM
The DOM is the tree of nodes the browser builds from your HTML. Find a node with document.querySelector and change it with textContent.
Try it
- DOM explorer – A small page and its DOM tree: click a node to see how JavaScript finds it, and change its text.
Transcript
When a browser opens your H T M L, it builds a tree of objects in memory. This tree is called the D O M, the Document Object Model. Every element is a node in the tree.
JavaScript can reach the page through the document object. The query selector method finds one element, using the same selectors as C S S.
Once you have the element, you can change it. Set its text content, and the page changes at once. The H T M L file stays the same. Only the tree in the browser changes.
To run your script, add a script tag at the end of the body, so the elements already exist. Then open the console to try things out.
Remember: the D O M is the tree the browser builds from your page. Use document dot query selector to find a node, and text content to change it.
More in this series
1:2624What is Git?
Git remembers every saved version of a folder. Repository, commit, and the four first commands: git status, add, commit and log.
1:1926Events in the browser
An event is something that happens on the page. addEventListener waits for it and runs a handler function, shown next to the same idea in Scratch.
1:1827Changing the page
Toggle a class with classList so CSS restyles an element, and build new elements with createElement and append, like a to-do list adding tasks.
1:1528Arrays and objects
An array is a numbered list, an object is a set of labelled values. An array of objects and a loop turn data into cards.
1:2429Local storage and JSON
localStorage is the browser's notebook for your site. JSON.stringify turns an array or object into text to save, and JSON.parse turns it back.
1:2630Fetch and JSON
The browser is the client and fetch sends the request. The server answers with JSON, async and await wait for it, and the Network tab shows what happened.
1:1631Debugging JavaScript
Find bugs in JavaScript: console.log to look, reading an error message and its line, and a breakpoint to pause and step through code in DevTools.