JS DOM - 02.05 - Styling

elem.style.width = '100px';
//works same as css 
width:100px
elem.style.backgroundColor = 
elem.style.zIndex = 
elem.style.borderLeftWidth =

document.body.style.backgroundColor = prompt('color?', 'green');

When accessing kebab-cased CSS property like background-colour with js, With dot notation, camelCase can be used. With bracket notation, both camelCase and kebab-case can be used but the property name must be a string.

div.style.background-color;
// this will not work as it tries to substract

div.style.backgroundColor;
// dot notion with camelCase works

div.style["background-color"];
// bracket notaion with kebab-case works
div.style["backgroundColor"];
// bracket notation with camelCase also works

Altering Elements Style

When there is a reference to an element, it can be used to alter the properties, attributes, class and styling of that element.

// create a new div element
const div = document.createElement("div");

div.style.color = 'blue';
div.style.padding = "10px";
div.style.backgroundColor = "red";
div.style.textAllign = "center";
div.style.width = "250px";

elem.style.cssText

Instead of assigning individual style with style. Full rewrite can be made with style.cssText. This is rarely used as it removes all existing styles. So mostly used for new elements.

// add several style rules
div.style.cssText = `color: blue;
	color: red !important;
	background-color: white;
	width: 100px;
	text-align: center;
	`;

The same can be accomplished by div.setAttribute('style', 'color: red...'

getComputedStyle(element, [pseudo])

elem.style cannot be used to read any anything from CSS class. is used to read the style.

getComputedStyle(document.body);