English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
styleSet or return the inline style of the element.
It returns aCSSStyleDeclarationan object that contains a list of all style properties of the element, and assigns values to the properties defined in the inline style attribute of the element.
Return style property:
element.style.property
Set style property:
element.style.property = value
document.getElementById("demo").style.color = "blue";Test and See‹/›
Note:Styles cannot be set by assigning a string to the style attribute, for exampleelement.style="color: blue;". To set the style of an element, append a "CSS" property to the style and specify a value, as shown below:
element.style.backgroundColor="blue"; //Set the background color of the element to blue
As you can see, the JavaScript syntax used to set CSS properties is similar to CSS (backgroundColor instead of background-color) is slightly different.
For a list of all available properties, seeStyle Object Reference.
The style attribute is not useful for fully understanding the styles applied to an element, because it only represents the CSS declarations set in the inline style attribute of the element, and does not represent the CSS declarations from other places (such as the style rules in this section) or external style sheets. To get the values of all CSS properties of an element, you should usewindow.getComputedStyle().
However, you can use document.getElementsByTagName() to access <style> elements from <head>:
var x = document.getElementsByTagName("style")[0]; //Get the first <style> element
Note:It is recommended to use the style attribute instead ofElement .setAttribute("style", "...")method, because the style attribute will not override other CSS properties that may be specified in the style attribute.
All browsers fully support the style attribute:
attribute | |||||
style | is | is | is | is | is |
value | description |
---|---|
value | Specify the value of the specified attribute. For example, for the border attribute: element.style.border="5px pure blue"; |
Return Value: | OneCSSStyleDeclarationObject representing the style attribute of the element |
---|---|
DOM Version: | CSS Object Model (CSSOM) |
Get the top boundary value of the <p> element:
var x = document.getElementById("demo").style.borderTop;Test and See‹/›
UseElement .setAttribute() method sets CSS style:
1px solid blue;Test and See‹/›
CSS Tutorial:CSS Tutorial
CSS Reference:Comprehensive List of CSS Properties
HTML Reference:HTML Style Properties
HTML Reference:HTML <style> tag