English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM style attribute

HTML DOM Element-Objekt

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 attributes of the element.

Syntax:

Return style attribute:

element.style.property

Set style attribute:

element.style.property = value
document.getElementById("demo").style.color = "blue";
Testen Sie heraus‹/›

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" attribute 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 attributes, seeStyle Object Reference.

The style attribute is not useful for fully understanding the styles applied to an element, as it only represents the CSS declarations set in the inline style attributes 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 does not override other CSS properties that may be specified in the style attribute.

Browser compatibility

All browsers fully support the style attribute:

attribute
styleisisisisis

attribute value

valuedescription
valueSpecify the value of the specified attribute. For example, for the border attribute:
element.style.border="5px reines Blau";

Technische Details

Rückgabewert:einCSSStyleDeclarationObjekt, das die Style-Eigenschaft des Elements darstellt
DOM-Version:CSS-Objektmodell (CSSOM)

Mehr Beispiele

Gewinnen Sie den oberen Randwert des <p>-Elements:

var x = document.getElementById("demo").style.borderTop;
Testen Sie heraus‹/›

verwendenElement .setAttribute() Methode setzt CSS-Style:

var div = document.querySelector("#myDiv");
div.setAttribute("style", "color:red; border:") 1px fest blau;");
Testen Sie heraus‹/›

Verwandte Referenzen

CSS-Tutorial:CSS-Tutorial

CSS-Referenz:Vollständiges Verzeichnis der CSS-Attribute

HTML-Referenz:HTML-Style-Attribute

HTML-Referenz:HTML <style>-Tag

HTML DOM Element-Objekt