Last Updated: November 5, 2020
Share this:
Basics JavaScript CSS

How to Quickly Add Inline CSS Styles Through JavaScript

If you've ever tried to modify your inline CSS from JavaScript, you'll notice it can be quite verbose.

// Don't do this
const button = document.querySelector('#button');
button.addEventListener('click', () => {
	button.style.border = '1px solid blue';
    button.style.borderRadius = '2px';
    button.style.color = 'white';
    // and so it goes
});

I'm going to start by saying that the best way of adding styles through JavaScript is through CSS classes.

This lets you keep all your visual logic in one place, and have more complicated interactions between page elements, such as having child elements update too.

const button = document.querySelector('#button');
button.addEventListener('click', () => {
    button.classList.add('clicked');
});
#button.clicked {
	border: 1px solid blue;
    border-radius: 2px;
    color: white
}

#button.clicked span {
	color: red;
}

If you're doing something where classes don't work (such as JavaScript animations), another way to apply multiple styles is through Object.assign.

const button = document.querySelector('#button');
button.addEventListener('click', () => {
	Object.assign(button.style, {
    	border: '1px solid blue',
        borderRadius: '2px',
        color: 'white'
    });
});

Can't get past JavaScript Tutorials?

Download my FREE ebook on how to succeed as a self-taught JavaScript Developer, and how to find projects that you'll actually finish. Learn More...

Share this: