js set style css code example

Example 1: add style javascript

// Bad:
element.setAttribute("style", "background-color: red;");
// Good:
element.style.backgroundColor = "red";

Example 2: js add css style to element

// Create our stylesheet
var style = document.createElement('style');
style.innerHTML =
	'.some-element {' +
		'color: purple;' +
		'background-color: #e5e5e5;' +
		'height: 150px;' +
	'}';

// Get the first script tag
var ref = document.querySelector('script');

// Insert our new styles before the first script tag
ref.parentNode.insertBefore(style, ref);

Example 3: change style js

// select element from DOM
const el = document.querySelector('.para')
// change css style
el.style.color = 'purple'

Tags:

Css Example