Skip to content

Instantly share code, notes, and snippets.

@fabriciofmsilva
Last active July 26, 2019 20:35
Show Gist options
  • Save fabriciofmsilva/6df66e88234b6d5462d7d067af739a44 to your computer and use it in GitHub Desktop.
Save fabriciofmsilva/6df66e88234b6d5462d7d067af739a44 to your computer and use it in GitHub Desktop.
Add CSS in JS
.btn {
	background-color: red;
	color: white;
	padding: 20px;
}
// Get the element
var button = document.querySelector('button');

// Add the class
button.classList.add('btn');
// Get the element
var button = document.querySelector('button');
// Setup the styles object
var styles = {
backgroundColor: 'red',
color: 'white',
padding: '20px'
};
// Add the styles to the element
Object.assign(button.style, styles);
// Create styles
var styles = [
'.btn {',
'background-color: red;',
'color: white;',
'padding: 20px;',
"}"
].join('');
// Get the head element
var head = document.head || document.getElementsByTagName('head')[0];
// Inject styles into the DOM
var style = document.createElement('style');
style.textContent = styles;
head.appendChild(style);
// Get the element
var button = document.querySelector('button');
// Add the class
button.classList.add('btn');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment