Styling Elements
Styling in JavaScript is where things get a little more visual. It’s no longer just about logic and data—now you're actually changing how things look on the page. Want a button to turn red when someone clicks it? Or hide an element when a user submits a form? That’s where styling with JavaScript kicks in.
.style property
The .style
property gives you direct access to an element’s inline styles—meaning the styles that are written directly on the element in the HTML. You can read from it or write to it.
const box = document.querySelector('.box');
box.style.backgroundColor = 'lightblue';
box.style.border = '2px solid navy';
This will immediately apply the styles to the element, as if you had written:
<div class="box" style="background-color: lightblue; border: 2px solid navy;"></div>
Notice the JavaScript version uses camelCase (e.g., backgroundColor
) instead of the usual CSS kebab-case (background-color
). That’s just how the .style
object works.
But here's the catch: .style
only changes or reads inline styles. If the background color was set via a CSS file or a <style>
tag, you won’t see that value when you check element.style.backgroundColor
. It’s strictly what’s in the style=""
attribute.
So .style
is good for quick changes, but not ideal for managing consistent design. For that, we go to classes.
.className and .classList
If you're serious about keeping your styling organized (and you should be), you’ll want to work with CSS classes instead of inline styles.
.className
This gives you the entire string of class names on an element. You can set it or read it:
const card = document.querySelector('.card');
card.className = 'highlighted';
Be careful—this replaces all existing classes. If you wanted to add a class without nuking the rest, use .classList
.
.classList
This is the modern, flexible way to work with classes. It gives you methods to add, remove, or toggle classes without affecting others.
const button = document.querySelector('.btn');
button.classList.add('active');
button.classList.remove('disabled');
button.classList.toggle('hidden');
add()
→ Adds a class.remove()
→ Removes a class.toggle()
→ Adds the class if it’s not there, removes it if it is.
You can even check if an element has a certain class:
if (button.classList.contains('active')) {
console.log('Button is active!');
}
Using .classList
keeps your styles clean and reusable, and keeps the separation between JavaScript and CSS logic, which is a big deal when building maintainable web apps.