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
});

It's dirty, and probably fine for a small, isolated change... but it quickly spells disaster when your project grows, and your codebase gets clogged with lines upon lines of CSS changes.

Best Method: Use Classes

Hands down, the best way of adding styles through JavaScript is through CSS classes.

Aside from keeping your visual logic in one place, CSS classes will let you update multiple elements (such as children elements) with a single line of JavaScript.

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;
}

Alternate Method: Object.assign

If you're doing something where classes don't work (such as JS-powered animations), there is still a better way to apply multiple styles than one at a time – Object.assign.

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

This is especially powerful in situations where you have a set of styles that you need to apply over and over again.

const baseStyles = {
	borderRadius: '2px'
};

// ...
button.addEventListener('click', () => {
	Object.assign(button.style, {
    	...baseStyles,
        border: '1px solid blue'
    });
}

These are simple techniques, but they're a life-saver when you're trying to keep a clean code-base.

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...