js add css to element code example

Example 1: add style javascript

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

Example 2: javascript change attribute

var element = document.getElementById("elemId");
element.setAttribute("attributeName", "value");

Example 3: how to give css style in javascript

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

Example 4: add css in javascript

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

Example 5: 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 6: style through javascript

element.style.backgroundColor = "red";   // set the background color of an element to red

Tags:

Css Example