Skip to main content

Changing what’s on the page

Once you’ve selected an element, you can change anything about it — its text, HTML, styles, classes, and attributes. This is how vanilla JavaScript makes pages dynamic.

Changing text content

textContent — plain text

textContent sets or gets the plain text of an element. It’s safe — any HTML in the string is displayed as text, not rendered.

innerHTML — HTML content

innerHTML parses and renders HTML. Use it when you need to insert structured content.
Never set innerHTML with user input. It creates a cross-site scripting (XSS) vulnerability. If a user types <script>alert('hacked')</script>, it will execute. Use textContent for user-provided data.

When to use each

Default to textContent. Only use innerHTML when you specifically need to set HTML, and never with user input.

Changing styles

Inline styles

CSS property names use camelCase in JavaScript:

Removing an inline style

element.style only reads and sets inline styles. It won’t show styles from your CSS files. To read the computed (final) style, use getComputedStyle(element).

Adding and removing classes

This is the preferred way to change styles. Instead of setting individual CSS properties, toggle classes that are defined in your stylesheet.

classList API

Practical examples

Prefer classList over element.style for most visual changes. CSS classes are reusable, easier to maintain, and keep your JavaScript focused on logic rather than styling.

Changing attributes

setAttribute / getAttribute

Direct property access

Most common attributes have matching properties:

data attributes

Custom data-* attributes are accessed through the dataset property:
data-* attributes are always strings. If you store a number, you’ll need to convert it: Number(card.dataset.userId).

Showing and hiding elements

Three common patterns:
The CSS class approach is cleanest. Define a .hidden class in CSS and toggle it with classList.toggle("hidden"). This keeps your styling in CSS and your logic in JavaScript.

What’s next?

You can modify existing elements. Now let’s learn how to create new elements from scratch and add them to the page.

Creating elements

Dynamically add new HTML elements to the page