style property is used to get as well as set the inline style of a DOM element using different CSS properties. It returns a
CSSStyleDeclaration object, which contains a list of all CSS properties defined in the element's
style attribute without any effects on the adjacent elements.
To access the
style property, you can use the
getElementById() method as shown below:
const elem = document.getElementById('sidebar'); // get CSS property console.log(elem.style.display); // set CSS property elem.style.display = 'block';
The following example demonstrates how to change the color and font CSS properties of an HTML element with
id="about" using the
const elem = document.getElementById('about'); // change text color to blue elem.style.color= 'blue'; // change fonts elem.style.fontWeight = 'bold'; elem.style.fontSize = '18px';
The above code will change the text color of the HTML element to blue, make it bold, and set the font size to
You can not set a CSS property by assigning a string directly to the style property:
// set property directly (wrong) elem.style = 'color: blue';
style property is ready-only, as the
style attribute returns a read-only
CSSStyleDeclaration object. Instead, you can use the
style property to set or get the individual CSS property. Preferably, you should use the
style property to set specific styles to an HTML element without changing other style values.
To completely override the existing inline styles for an element, the
style property provides the
elem.style.cssText = 'color: blue; font-weight: bold; font-size: 18px';
Alternatively, you can use the element's
setProperty() method to specify
style attribute value:
elem.setAttribute('style', 'color: blue; font-weight: bold; font-size: 18px');
Take a look at this guide to find out all CSS properties accessible using the
styleproperty is only useful to get the style rules set in the element's inline
<div style="color: blue">, and not those that come from elsewhere, such as style rules defined using the
<style>elements, or external style sheets.
-) in their names such as
font-size becomes the DOM property
borderLeftColor, and so on.
👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5) .
Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.