Changing the Page
Once you've selected an element, you can change everything about it: its text, its HTML, its attributes, its classes and styles. You can also create brand-new elements and add them to the page, or remove existing ones. This is how interactive interfaces are built.
Changing text and HTML
| Property | Reads / writes |
|---|---|
textContent | Plain text. Any < or > is shown literally — safe for user input |
innerHTML | HTML markup, parsed into elements |
innerHTML. A "name" like <img src=x onerror="stealCookies()"> would run as code. Use textContent for anything that came from a user, a URL or an API.Attributes and properties
Most standard attributes are available as properties (href, src, alt, value, disabled). For anything else, use getAttribute, setAttribute, removeAttribute and hasAttribute. Custom data-* attributes appear on element.dataset, with dashed names converted to camelCase (data-user-id → dataset.userId).
Classes
The classList API is the cleanest way to change appearance — toggle classes and let CSS do the styling:
classList has add, remove, toggle, contains and replace. toggle("x", condition) adds or removes based on a boolean.
Inline styles
CSS property names become camelCase (background-color → backgroundColor). element.style only reads inline styles; use getComputedStyle(element) to read the final value after all stylesheets apply. Prefer toggling classes over setting many inline styles.
Creating and inserting elements
| Method | Inserts… |
|---|---|
parent.append(...nodes) | At the end, inside |
parent.prepend(...nodes) | At the start, inside |
el.before(...) / el.after(...) | Right before / after the element, as a sibling |
el.replaceWith(...) | In place of the element |
el.insertAdjacentHTML(pos, html) | HTML at beforebegin, afterbegin, beforeend or afterend |
append also accepts plain strings, which are inserted as text. When adding many elements, build them in a DocumentFragment (or an array passed to one append call) to update the page once instead of many times.
Removing and cloning
cloneNode(true) copies an element with all its children (but not its event listeners). The HTML <template> element is designed for exactly this: inert markup you clone to stamp out repeated components.
Showing and hiding
Set element.hidden = true to hide an element (equivalent to the hidden HTML attribute), or toggle a class that sets display: none. Both keep the element in the DOM, ready to show again.