Borislav Hadzhiev
Thu Mar 31 2022·2 min read
Photo by Conner Baker
To set CSS styles on an element in TypeScript:
style
object of the element to update its styles.el.style.backgroundColor = 'lime'
.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Hello world</div> <script src="./src/index.ts"></script> </body> </html>
And here is the related TypeScript code.
// 👇️ const box: HTMLElement | null const box = document.getElementById('box'); if (box != null) { box.style.backgroundColor = 'lime'; box.style.color = 'white'; box.style.fontSize = '2em'; }
We used the
document.getElementById
method to select the element. The method returns null
if no element with the
provided id
exists in the DOM, so we had to make sure the box
variable
doesn't store a null
value before accessing any properties on it.
If you use the document.getElementsByClassName method instead, type the elements as a collection of html elements.
const boxes = Array.from( document.getElementsByClassName('box') as HTMLCollectionOf<HTMLElement>, ); boxes.forEach(box => { box.style.backgroundColor = 'lime'; box.style.color = 'white'; box.style.fontSize = '2em'; });
The getElementsByClassName
method returns a type of
HTMLCollectionOf<Element>
and the Element
interface does not contain the
style
property.
This is why we used a
type assertion
to type the collection as HTMLCollectionOf<HTMLElement>
.
We used the style
object to set CSS properties on the element.
style
object.If you don't like CSS property names being camel-cased, you can use the setProperty method instead.
// 👇️ const box: HTMLElement | null const box = document.getElementById('box'); if (box != null) { box.style.setProperty('background-color', 'lime'); box.style.setProperty('color', 'white'); }
The setProperty
method takes the following 3 parameters:
propertyName
- the name of the CSS property we want to modify. Note that
property names of multiple words must be hyphenated.value
- the new value for the CSS property.priority
- can be set to important
or empty string.You can also use the style
object to read CSS property values from the
element.
// 👇️ const box: HTMLElement | null const box = document.getElementById('box'); if (box != null) { box.style.setProperty('background-color', 'lime'); // 👇️ "lime" console.log(box.style.backgroundColor); // 👇️ "16px" console.log(window.getComputedStyle(box).fontSize); }
The first example reads the value of the background color property on the element.
However, this wouldn't work if the property was not set as an inline style on the element.
window.getComputedStyle
method instead.The getComputedStyle
method returns an object that contains the values of all
CSS properties of the passed in element, after applying stylesheets.