Changing the DOM
As a designer you already think in layers and states — a button in its default state, its hover state, its active state. JavaScript lets you flip between those states live in the browser. The bridge between your code and what the user sees is called the DOM.
What is the DOM?
Section titled “What is the DOM?”The DOM (Document Object Model) is the browser’s live, in-memory model of your page. Think of it like Figma’s layer tree: every element on the page has a corresponding node in the tree, and JavaScript can read or modify any of them in real time.
When JavaScript changes the DOM, the browser immediately reflects that change on screen — no page reload required.
Two techniques worth knowing right away
Section titled “Two techniques worth knowing right away”1. Change text with .textContent
Section titled “1. Change text with .textContent”Every element has a .textContent property that holds the visible text inside it. Assigning a new string replaces that text instantly:
var heading = document.querySelector('h1');heading.textContent = 'Hello, world!';2. Toggle a CSS class with .classList.toggle
Section titled “2. Toggle a CSS class with .classList.toggle”Elements also have a .classList object that lets you add, remove, or toggle CSS classes. .classList.toggle('class-name') works like a light switch:
- If the class is absent, it adds it.
- If the class is present, it removes it.
This maps directly to toggling a variant state in Figma — the element just switches between two visual styles defined in your CSS.
var card = document.querySelector('.card');card.classList.toggle('highlighted');Try it live
Section titled “Try it live”The demo below has a card and a button. Each click toggles a highlighted CSS class on the card and updates the button’s label to match the current state.
How the code works
Section titled “How the code works”document.querySelector('#card')finds the card element by itsidand stores a reference in thecardvariable.document.querySelector('#toggleBtn')does the same for the button.btn.addEventListener('click', function() { ... })tells the browser to run the function every time the button is clicked.- Inside the function,
card.classList.toggle('highlighted')flips the class on or off. card.classList.contains('highlighted')checks the current state so the button label can stay in sync via.textContent.