Use Sophia to knock out your gen-ed requirements quickly and affordably. Learn more
×

JavaScript Style and Class Control

Author: Sophia

what's covered
In this lesson, you will learn how to modify element styles and toggle CSS classes dynamically using JavaScript. By combining JavaScript with CSS, you can create interactive web pages that respond to user actions with visual changes. Specifically, this lesson will cover the following:

Table of Contents

1. Inline Styles

JavaScript can directly change how elements appear on the page using the style property. This makes it possible to update styles instantly in response to user actions, without modifying your stylesheet.

1a. 'style' Property

Every DOM element includes a style property, which represents its inline styles. It allows JavaScript to set or read individual CSS property values directly on an element.

EXAMPLE

You can change a single style as such as an element’s background color:

const box = document.querySelector('.box');
box.style.backgroundColor = 'blue';
In this code:

  • document.querySelector('.box') selects an element with the class box
  • .style.backgroundColor accesses the background-color CSS property
  • Assigning 'blue' immediately changes the element’s background color, overriding any value set in a stylesheet

Additionally, you can modify multiple style properties on the same element by accessing different properties of the style object.

EXAMPLE

Setting multiple styles on one element:

const heading = document.querySelector('h1');
heading.style.color = 'navy';
heading.style.fontSize = '32px';
heading.style.textAlign = 'center';
In this code:

  • Each line modifies a different CSS property on the same h1 element
  • color, fontSize, and textAlign each correspond to a CSS property
  • The element updates visually after each assignment

In addition to setting styles, you can use the style property to check the current value of a CSS property. If a style is applied through a stylesheet rather than inline, the style property will not return it, so the result may be an empty string if no inline value exists.

EXAMPLE

To read the current inline style of an element, access the property without assigning a new value.

const currentColor = heading.style.color;
console.log(currentColor); // Output: "navy"

key concept
The style property is used to directly control inline styles on an element. It can both set new values and read existing ones, but it only reflects styles applied inline, not those from stylesheets.

try it
Open index.html in your Codespace. Confirm it contains an <h1> heading and at least one <p> element; if either is missing, add them now. Open js/scripts.js.

Preview the page in your browser.

Open the browser console (right-click the page and select “Inspect,” then click the “Console” tab).

In the console, type the following to select the heading and store it in a variable:

Copy
const heading = document.querySelector('h1');
Press “Enter” to run the code.

On a new line in the console, change the heading’s color:

Copy
heading.style.color = 'darkgreen';
Press “Enter” and observe the change in the preview.

Next, change the font size:

Copy
heading.style.fontSize = '40px';
Press “Enter” again and confirm the heading updates visually.

How would you read back the font size you just set?
const size = heading.style.fontSize;
console.log(size); // Output: "40px"
Since you set the font size through JavaScript (inline), the style property returns "40px". If the font size had been set in an external stylesheet instead, heading.style.fontSize would return an empty string.

term to know
Style Property
A property on DOM elements that represents inline CSS styles and allows JavaScript to read and set individual style values.

1b. camelCase Conversion

CSS property names often contain hyphens, such as background-color or font-size. JavaScript identifiers cannot contain hyphens because the hyphen character is interpreted as the subtraction operator. To bridge this gap, CSS property names are converted to camelCase when accessed through JavaScript.

The conversion follows a consistent pattern: remove the hyphen and capitalize the letter that follows it.

 An illustration of how CSS property names convert to JavaScript camelCase by removing hyphens and capitalizing the next letter, with examples like background-color to backgroundColor.

Using this conversion pattern, you can write CSS properties in JavaScript.

EXAMPLE

Converting CSS properties to JavaScript:

const card = document.querySelector('.card');

// CSS: background-color becomes backgroundColor
card.style.backgroundColor = '#f0f0f0';

// CSS: border-radius becomes borderRadius
card.style.borderRadius = '8px';

// CSS: box-shadow becomes boxShadow
card.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)';
In this code:

  • Each comment shows the CSS property name and its camelCase JavaScript equivalent
  • Hyphens are removed and the following letter is capitalized
  • The values remain the same strings you would use in CSS

Single-word CSS properties like color, margin, padding, and display remain unchanged because they contain no hyphens.

element.style.color = 'red';
element.style.margin = '20px';
element.style.display = 'none';

try it
What is the correct JavaScript property name for the CSS property text-decoration?
The correct JavaScript property name is textDecoration. Remove the hyphen and capitalize the “d” that follows it.

element.style.textDecoration = 'underline';

hint
When converting CSS to JavaScript, think of the hyphen as a signal to capitalize. The word after each hyphen gets its first letter capitalized, and then all the words join together without spaces or hyphens.


2. classList API

While the style property modifies individual CSS properties, the classList property allows JavaScript to work with an element’s CSS classes as a group. You can use it to add, remove, toggle, or check for classes on an element.

Illustration of classList methods: add, remove, toggle, and contains applied to a button with classes ‘btn’ and ‘primary’, showing how classes are added, removed, toggled, or checked.

term to know
classList
A property on DOM elements that provides methods for manipulating an element’s CSS classes, including add(), remove(), toggle(), and contains().

2a. 'add', 'remove', and 'toggle'

The three most commonly used classList methods are add(), remove(), and toggle(). Each method changes an element’s classes in a different way.

Use add() to apply one or more classes to an element. This is useful when you want to activate a style or state.

EXAMPLE

const button = document.querySelector('button');
button.classList.add('active');
button.classList.add('primary', 'large');
In this code:

  • add() applies one or more classes to the element
  • If a class is already present, it is not added again

Use remove() to take classes away from an element. This is useful when a state is no longer needed.

EXAMPLE

button.classList.remove('active');
button.classList.remove('primary', 'large'); // Remove multiple classes
In this code:

  • remove() deletes one or more classes from the element
  • If a class is not present, nothing happens

You can use toggle() to switch a class on or off. This is especially useful for interactive features where something needs to change state.

EXAMPLE

Building a dark mode toggle:

HTML code:

<button id="theme-toggle">Toggle Dark Mode</button>
Give feedback
const toggleButton = document.querySelector('#theme-toggle');

toggleButton.addEventListener('click', function() {
document.body.classList.toggle('dark-mode');
});

CSS code:

body {
background-color: white;
color: black;
}

body.dark-mode {
background-color: #1a1a1a;
color: white;
}
In this code:

  • The CSS defines two visual states
  • toggle() switches between those states with each click
  • JavaScript controls behavior, while CSS controls appearance

try it
Open index.html in your Codespace. If it does not already contain a <button>, add one such as:

Copy
<button>Click Me</button>
Give feedback
In your CSS file, create two classes:

Copy
.highlight {
background-color: yellow;
}

.dim {
background-color: gray;
opacity: 0.6;
}
In js/scripts.js, select the button:

Copy
const button = document.querySelector('button');
Add a click event listener that toggles the highlight class:

Copy
button.addEventListener('click', function() {
button.classList.toggle('highlight');
});
Save and preview your page in Codespace.

  • Click the button several times and observe how its appearance changes.
  • Open the “Elements” panel in DevTools to watch the class attribute update with each click.
What happens if you call classList.add('highlight') when the element already has the highlight class?
Nothing happens. The add() method does not create duplicate classes. Similarly, remove() does nothing if the class is not present, so both methods are safe to use without checking first.

2b. 'contains'

So far, you have used classList methods to change an element’s classes. You can also check whether a class is present. The contains() method checks whether an element has a specific class. It returns true if the class is present and false if it is not. This method helps you make decisions based on an element’s current state.

The contains() method is often used with conditional statements to control behavior based on an element’s current state.

EXAMPLE

Checking class presence before acting:

const menu = document.querySelector('.menu');

if (menu.classList.contains('open')) {
console.log('Menu is open');
} else {
console.log('Menu is closed');
}
In this code:

  • classList.contains('open') returns a Boolean value
  • The if statement uses that Boolean to run different code depending on the menu’s state
  • This pattern is useful when you need different behavior based on an element’s current class

You can also use contains() to control how elements are updated or styled.

EXAMPLE

Conditional styling based on class presence:

const notification = document.querySelector('.notification');

function dismissNotification() {
if (notification.classList.contains('visible')) {
notification.classList.remove('visible');
notification.classList.add('dismissed');
}
}
In this code:

  • The function first checks whether the notification has the visible class
  • Only if visible is present does it remove that class and add dismissed
  • This prevents dismissing a notification that is already hidden

try it
Write a line of code that checks if an element stored in the variable sidebar has the class minimized.
sidebar.classList.contains('minimized')
This expression returns true if the sidebar has the minimized class and false otherwise. You could use it inside an if statement to run different code depending on the sidebar’s state.

big idea
The classList API provides four key methods: add() adds classes, remove() removes classes, toggle() switches classes on and off, and contains() checks for class presence. These methods make it easy to change an element’s appearance by leveraging CSS classes defined in your stylesheet.


3. Styles Versus Classes

Both inline styles and CSS classes can change an element’s appearance, but each approach has distinct advantages. Choosing the right one depends on whether the value is dynamic or represents a predefined state.

Inline styles work best when you need values that are calculated at runtime—positions based on mouse coordinates, sizes computed from user input, or colors generated dynamically. Because these values cannot be predetermined in a stylesheet, setting them directly through the style property is the natural choice.

Comparison of inline styles and CSS classes, showing when to use each, example syntax, and key advantages such as dynamic values for styles and reusable, state-based styling for classes.

You can use inline styles to position an element based on calculated values:

EXAMPLE

Setting a dynamic position based on calculation:

const tooltip = document.querySelector('.tooltip');
const mouseX = 150;
const mouseY = 200;

tooltip.style.left = mouseX + 'px';
tooltip.style.top = mouseY + 'px';
In this code:

  • The left and top values depend on runtime calculations (mouse position)
  • These values change continuously and cannot be defined in advance with CSS classes
  • String concatenation appends 'px' to the numeric values

Inline styles work well for dynamic values, but many styling changes represent fixed states. In those cases, CSS classes are a better option. Classes keep your JavaScript cleaner by centralizing style definitions in your CSS file. They also enable pseudoelements, pseudoclasses, and CSS transitions, none of which are available through inline styles.

EXAMPLE

Using classes for state changes:

.button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
cursor: pointer;
}

.button.loading {
background-color: #6c757d;
cursor: wait;
}

.button.loading::after {
content: ' Loading...';
}

const submitButton = document.querySelector('.button');

function startLoading() {
submitButton.classList.add('loading');
}

function stopLoading() {
submitButton.classList.remove('loading');
}
In this code:

  • The .loading class changes the button’s appearance and cursor to indicate a pending action
  • The ::after pseudoelement appends "Loading..." text—this is only possible with CSS classes, not inline styles
  • JavaScript only needs to add or remove one class name to control multiple style changes at once

The following table summarizes when to reach for each approach:

Criteria Inline Styles CSS Classes
Value source Calculated at runtime Predefined in CSS
Typical use Positions, dynamic sizes, generated colors States (active, hidden, error)
Pseudoelements/classes Not available Available
CSS transitions Must be defined separately in CSS Defined alongside the class
Reusability One element at a time Reusable across multiple elements
Maintenance Values live in JavaScript Values live in CSS

hint
If you can describe the change with a word or phrase (like “active,” “hidden,” or “error”), it probably belongs in a class. If you need a specific number (like “247 pixels from the left”), use an inline style.

try it
You need to highlight a search result by changing its background to yellow.
Should you use an inline style or a CSS class? Why?
You should use a CSS class. The highlight is a predefined state (highlighted or not highlighted), and the yellow color is a fixed value, not a calculated one. Using a class like .highlighted { background-color: yellow; } keeps the style definition in your CSS and makes it easy to change the highlight color later without modifying JavaScript.

big idea
Choose inline styles for dynamic, calculated values that change at runtime. Choose CSS classes for predefined states and reusable style sets. This decision keeps your code organized and maintainable while taking advantage of each technique’s strengths.


4. Dynamic Visual Effects

Dynamic visual effects happen when JavaScript responds to user actions and updates styles or classes. These effects generally fall into two patterns: showing and hiding elements and providing interactive feedback.

4a. Show and Hide

One of the simplest visual effects is showing and hiding elements. This happens when JavaScript changes how an element is displayed in response to an action, such as a button click.

You can accomplish this by directly modifying a style property or by toggling a CSS class. Each approach has different advantages.

Using inline styles is the most direct way to show or hide an element.

EXAMPLE

Using inline style to hide an element:

const modal = document.querySelector('.modal');

function hideModal() {
modal.style.display = 'none';
}

function showModal() {
modal.style.display = 'block';
}
In this code:

  • Setting display to 'none' removes the element from the page layout entirely
  • Setting display to 'block' makes it visible again
  • This approach is simple but abrupt—the element disappears instantly

While inline styles work for quick changes, using CSS classes provides more flexibility and allows for smoother visual effects.

EXAMPLE

Using classes with CSS transitions:

.modal {
opacity: 1;
transition: opacity 0.3s ease;
}

.modal.hidden {
opacity: 0;
pointer-events: none;
}

const modal = document.querySelector('.modal');

function hideModal() {
modal.classList.add('hidden');
}

function showModal() {
modal.classList.remove('hidden');
}
In this code:

  • The CSS transition creates a smooth fade effect when the class changes
  • pointer-events: none prevents clicks on the invisible element
  • JavaScript only adds or removes the hidden class—the animation is handled entirely by CSS

These same techniques can be used to build interactive components such as menus and dropdowns.

step by step
Creating a toggle button for a dropdown menu includes these steps:

  1. Create the HTML structure with a button and menu container.
  2. Define CSS classes for the open and closed states.
  3. Add a click event listener to the button.
  4. Use classList.toggle() to switch the menu state.
<div class="dropdown">
<button class="dropdown-button">Menu</button>
<ul class="dropdown-menu">
<li>Option 1</li>
<li>Option 2</li>
<li>Option 3</li>
</ul>
</div>

.dropdown-menu {
display: none;
}

.dropdown-menu.open {
display: block;
}

const button = document.querySelector('.dropdown-button');
const menu = document.querySelector('.dropdown-menu');

button.addEventListener('click', function() {
menu.classList.toggle('open');
});

4b. Interactive Feedback

Showing and hiding elements is one type of visual effect. Another common pattern is interactive feedback, where the page responds visually to a user’s actions. These changes help users understand that something has happened, making the interface feel more responsive and intuitive.

One common form of interactive feedback is changing how a button looks while it is being pressed.

EXAMPLE

Button feedback on click:

.button {
background-color: #007bff;
transform: scale(1);
transition: transform 0.1s ease;
}

.button.clicked {
transform: scale(0.95);
}

const button = document.querySelector('.button');

button.addEventListener('mousedown', function() {
button.classList.add('clicked');
});

button.addEventListener('mouseup', function() {
button.classList.remove('clicked');
});
In this code:

  • The mousedown event fires when the user presses the button, adding the clicked class
  • The mouseup event fires when the user releases, removing the class
  • The CSS transition creates a subtle shrink effect that makes the button feel pressable

Interactive feedback is also useful in forms where visual changes can help users understand whether their input appears valid.

EXAMPLE

Providing validation feedback as the user types:

.input-field {
border: 2px solid #ccc;
}

.input-field.valid {
border-color: #28a745;
}

.input-field.invalid {
border-color: #dc3545;
}

const emailInput = document.querySelector('#email');

emailInput.addEventListener('input', function() {
const isValid = emailInput.value.includes('@');

if (isValid) {
emailInput.classList.remove('invalid');
emailInput.classList.add('valid');
} else {
emailInput.classList.remove('valid');
emailInput.classList.add('invalid');
}
});
In this code:

  • The input event fires each time the user types a character
  • A simple check determines whether the value contains an @ symbol
  • The code removes one class and adds another to switch between valid and invalid border colors
  • This gives the user real-time visual feedback as they type

key concept
Interactive feedback connects user actions to visual changes on the page. By combining event listeners with class or style updates, JavaScript can help interfaces respond clearly and immediately to user input.

So far, you’ve used class changes and event listeners to create simple visual effects. Next, you will combine these skills to build a more complete interactive interface.

before you start
Create a new file called interactive-cards.html in your Codespace. Add the following starter HTML:

Copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Cards</title>
<style>
body { font-family: sans-serif; padding: 20px; }
.card-container { display: flex; gap: 16px; flex-wrap: wrap; }
.card {
border: 2px solid #ccc;
border-radius: 8px;
padding: 16px;
width: 200px;
cursor: pointer;
transition: all 0.2s ease;
}
.card.selected {
border-color: #007bff;
background-color: #e7f1ff;
transform: scale(1.03);
}
.card h3 { margin: 0 0 8px; }
.card p { margin: 0; color: #555; }
#status { margin-top: 16px; font-weight: bold; }
</style>
</head>
<body>
<h1>Choose Your Interests</h1>
<div class="card-container" id="card-container"></div>
<p id="status">No interests selected.</p>
<script src="cards.js"></script>
</body>
</html>
Then, create a file called cards.js with the following starter code:

Copy
const container = document.querySelector('#card-container');
const status = document.querySelector('#status');
Add a link to this page in your index.html, and then preview your site and open the page.

try it
Build an interactive card selection interface step by step:

1. Create and display cards:

  • Use document.createElement() to create at least three card elements.
  • Add the class card to each element.
  • Use innerHTML to give each card a title and description.
  • Use appendChild() to add each card to the container.
Preview your page and confirm the cards appear.

2. Add click behavior:

  • Add a click event listener to each card.
  • When a card is clicked, toggle the selected class.
Preview and confirm that clicking a card changes its appearance.

3. Update the status message:

  • Create a function that counts how many cards have the selected class.
  • Update the #status text based on the number selected.
Preview and confirm that the status text updates as you select and deselect cards.

Check your solution
Your solution may differ, but here is one approach:

const container = document.querySelector('#card-container');
const status = document.querySelector('#status');

// Create cards manually
const card1 = document.createElement('div');
card1.classList.add('card');
card1.innerHTML = '<h3>Music</h3><p>Click to select</p>';

const card2 = document.createElement('div');
card2.classList.add('card');
card2.innerHTML = '<h3>Travel</h3><p>Click to select</p>';

const card3 = document.createElement('div');
card3.classList.add('card');
card3.innerHTML = '<h3>Cooking</h3><p>Click to select</p>';

// Add cards to container
container.appendChild(card1);
container.appendChild(card2);
container.appendChild(card3);

// Function to update status
function updateStatus() {
const count = document.querySelectorAll('.card.selected').length;

if (count === 0) {
status.textContent = 'No interests selected.';
} else {
status.textContent = count + ' interest(s) selected.';
}
}

// Add click behavior to each card
card1.addEventListener('click', function() {
card1.classList.toggle('selected');
updateStatus();
});

card2.addEventListener('click', function() {
card2.classList.toggle('selected');
updateStatus();
});

card3.addEventListener('click', function() {
card3.classList.toggle('selected');
updateStatus();
});
Your card structure and descriptions may look different—the key is that clicking a card toggles its selected class and the status text updates to reflect the current selection count.

watch
Watch this video, to build an interactive card selection interface using HTML, CSS, and JavaScript.

summary
In this lesson, you explored inline styles using the style property, including how to set and read values and apply camelCase conversion for CSS properties in JavaScript. You then used the classList API, including add, remove, toggle, and contains, to manage classes and control element states more efficiently. You compared styles versus classes to determine when to use dynamic inline values versus predefined class-based styles. Finally, you applied these concepts to create dynamic visual effects, including show and hide behaviors and interactive feedback in response to user actions.

Source: THIS TUTORIAL WAS AUTHORED BY SOPHIA LEARNING. PLEASE SEE OUR TERMS OF USE.

REFERENCES

Mozilla Developer Network. (n.d.). How the web works. developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/How_the_Web_works

Terms to Know
Style Property

A property on DOM elements that represents inline CSS styles and allows JavaScript to read and set individual style values.

classList

A property on DOM elements that provides methods for manipulating an element’s CSS classes, including add(), remove(), toggle(), and contains().