--- title: ElementCSSInlineStyle.style slug: Web/API/ElementCSSInlineStyle/style tags: - API - CSSOM - HTMLElement - Property - Reference - SVGElement - Style translation_of: Web/API/ElementCSSInlineStyle/style ---
styleプロパティは、要素のインラインスタイルと同様に設定したり取得したりするために使用します。取得時は {{domxref("CSSStyleDeclaration")}} オブジェクトで、その要素のインラインの style 属性で定義された属性に割り当てられた値を持つ、その要素のすべてのスタイルプロパティのリストを返します。
style 経由でアクセス可能な CSS プロパティのリストについては、CSS プロパティリファレンスを参照してください。style プロパティは CSS カスケードで style 属性によるインラインスタイル宣言と同じ (かつ最高の) 優先順位を持ちます。
スタイルは style プロパティに (elt.style = "color: blue;" のように) 文字列で直接代入して設定しないでください。これは style 属性が読み取り専用であり、また CSSStyleDeclaration オブジェクトも読み取り専用だからです。代わりに、 style. のプロパティに値を代入してスタイルを設定できます。要素に対して特定のスタイルを他のスタイル値を変えずに追加するため、 style の個々のプロパティを (elt.style.color = '...'のように) 使うことをお勧めします。 elt.style.cssText = '...' や elt.setAttribute('style', '...') では要素のインラインスタイルを、既存のインラインスタイルを上書きすることで設定するからです。なお、 elt.style.<プロパティ> を使ってスタイルを設定する時、プロパティ名はキャメルケースであって、ケバブケースでないので注意してください (つまり elt.style.fontSizeとなり、 elt.style.font-sizeではありません)。
スタイル宣言は null または空文字を設定することでリセットします。例えば elt.style.color = null のようにします。 Internet Explorer は空文字列を設定する必要があり、 null に設定しても何も起こりません。
// Set multiple styles in a single statement
elt.style.cssText = "color: blue; border: 1px solid black";
// Or
elt.setAttribute("style", "color:red; border: 1px solid blue;");
// Set specific style while leaving other inline style values untouched
elt.style.color = "blue";
style プロパティは、要素に適用されているスタイルを完全に知るためには有用ではありません。これは、要素のインラインの style 属性に設定されている CSS 宣言のみを表し、 {{HTMLElement("head")}} セクションのスタイル規則や外部のスタイルシートなど、他の場所のスタイル規則に由来するものを表してはいないからです。要素のすべての CSS プロパティの値を取得するには、代わりに {{domxref("Window.getComputedStyle()")}} を使用する必要があります。
次のコードスニペットは、要素の style プロパティで取得する値と、getComputedStyle() で取得するものの違いを実演します。
<!DOCTYPE HTML>
<html>
<body style="font-weight:bold;">
<div style="color:red" id="myElement">..</div>
</body>
</html>
var element = document.getElementById("myElement");
var out = "";
var elementStyle = element.style;
var computedStyle = window.getComputedStyle(element, null);
for (prop in elementStyle) {
if (elementStyle.hasOwnProperty(prop)) {
out += " " + prop + " = '" + elementStyle[prop] + "' > '" + computedStyle[prop] + "'\n";
}
}
console.log(out)
出力されるコードは次のようなものです。
... fontWeight = '' > 'bold' color = 'red' > 'rgb(255, 0, 0)' ...
font-weight のスタイルの計算値に bold の値がありますが、要素の style プロパティにはないことに注意してください。
| 仕様書 | 状態 | 備考 |
|---|---|---|
{{SpecName('CSSOM', '#dom-elementcssinlinestyle-style', 'the ElementCSSInlineStyle.style property')}} |
{{Spec2('CSSOM')}} | 初回定義 |
{{Compat("api.HTMLElement.style")}}