Skip to content

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.

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.

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');

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.

  1. document.querySelector('#card') finds the card element by its id and stores a reference in the card variable.
  2. document.querySelector('#toggleBtn') does the same for the button.
  3. btn.addEventListener('click', function() { ... }) tells the browser to run the function every time the button is clicked.
  4. Inside the function, card.classList.toggle('highlighted') flips the class on or off.
  5. card.classList.contains('highlighted') checks the current state so the button label can stay in sync via .textContent.
What does `.classList.toggle('active')` do?
What does setting `.textContent` on an element do?
What is the DOM?