how to add css property in javascript code example

Example 1: access css property using javascript

const element = document.querySelector('.element')
const style = getComputedStyle(element)

Example 2: how to give css style in javascript

document.getElementById("myH1").style.color = "red";

Example 3: add css in javascript

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

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

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

Tags:

Html Example