how to set css in javascript code example

Example 1: how to change css with js

document.querySelector('h1', container).style.backgroundColor = 'red';

Example 2: add css in javascript

document.getElementById("demo").style.display = "none";

Example 3: 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 4: how to change css using javascript

document.getElementById("myText").className = "anyNewClass"

Tags:

Html Example