JSでスタイルを操作する基礎!element.style と window.getComputedStyle() の正しい使い分け
JavaScriptを使って要素のスタイル(色やサイズなど)を取得しようとしたとき、「CSSファイルにはちゃんと書いているのに、JSで取得したら空文字列になってしまった…」という経験はありませんか?
実は、JavaScriptでスタイルを扱う際、よく使われる element.style と window.getComputedStyle() には明確な役割の違いがあります。
今回は、この2つの決定的な違いと、それぞれの正しい使い分けについて、実際にブラウザ上で動作を確認できるデモを交えて分かりやすく解説します!
デモ動作
See the Pen getComputedStyle と element.style の違い by mikanbako (@mikanbako) on CodePen.
demo: getComputedStyle() と element.style の違い
実装コードの紹介
【HTML】
<div class="l-wrap">
<h2>スタイル取得・変更デモ</h2>
<!-- スタイルを確認・変更する対象のボックス -->
<div class="p-box js-box">
ターゲット要素
</div>
<div class="p-buttons">
<button class="c-btn js-btn-style">1. element.style で背景色を取得</button>
<button class="c-btn js-btn-computed">2. getComputedStyle で背景色を取得</button>
<button class="c-btn c-btn--red js-btn-set">3. element.style で背景色を変更</button>
<button class="c-btn js-btn-reset">4. スタイルをリセット(元に戻す)</button>
</div>
<!-- 結果表示エリア -->
<div class="p-result">
<p>取得結果:<span class="p-result__text js-result-text">ボタンを押してね</span></p>
</div>
</div>
【CSS】
.l-wrap {
color: #3e3e3e;
text-align: center;
padding: 40px 20px;
}
h2 {
font-weight: bold;
font-size: 18px;
margin-bottom: 24px;
}
/* ターゲット要素(CSSファイル側でスタイルを指定) */
.p-box {
width: 200px;
height: 100px;
background-color: #1bb4d4; /* 水色を指定 */
color: #fff;
display: flex;
justify-content: center;
align-items: center;
margin: 0 auto 30px;
border-radius: 8px;
font-weight: bold;
font-size: 20px;
transition: background-color 0.3s;
}
/* ボタン装飾 */
.p-buttons {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
margin-bottom: 30px;
}
.c-btn {
padding: 12px 24px;
font-size: 16px;
font-weight: bold;
background: #fff;
color: #333;
border: 2px solid #ddd;
border-radius: 8px;
cursor: pointer;
width: 100%;
max-width: 450px;
transition: all 0.2s;
}
.c-btn:hover { background: #f0f0f0; }
.c-btn--red { border-color: #c72c4c; color: #c72c4c; }
.c-btn--red:hover { background: #ffebee; }
/* 結果表示 */
.p-result {
background: #fff;
padding: 20px;
border-radius: 8px;
max-width: 450px;
margin: 0 auto;
border: 2px dashed #ccc;
}
.p-result__text {
font-weight: bold;
color: #c72c4c;
font-size: 20px;
}
【JavaScript】
const box = document.querySelector('.js-box');
const resultText = document.querySelector('.js-result-text');
// ① element.style で取得するボタン
document.querySelector('.js-btn-style').addEventListener('click', () => {
// インラインスタイル(タグに直接書かれたスタイル)のみを取得する
const styleValue = box.style.backgroundColor;
if (styleValue === "") {
resultText.textContent = "(空っぽ!)";
} else {
resultText.textContent = styleValue;
}
});
// ② getComputedStyle で取得するボタン
document.querySelector('.js-btn-computed').addEventListener('click', () => {
// CSSファイルなども含め、最終的にブラウザが計算したスタイルを取得する
const computedStyle = window.getComputedStyle(box);
resultText.textContent = computedStyle.backgroundColor;
// ※取得される値は rgb(27, 180, 212) のような形式になります
});
// ③ element.style で変更するボタン
document.querySelector('.js-btn-set').addEventListener('click', () => {
// インラインスタイルとして背景色を上書き(セット)する
box.style.backgroundColor = "#c72c4c";
resultText.textContent = "背景色を赤に変更しました!";
});
// ④ スタイルをリセットするボタン
document.querySelector('.js-btn-reset').addEventListener('click', () => {
// 空文字列 "" をセットすることでインラインスタイルを削除し、CSSファイルの設定に戻します
box.style.backgroundColor = "";
resultText.textContent = "スタイルをリセットしました!";
});
コードの解説・決定的な違い
element.style は「インラインスタイル」専用
// インラインスタイル(タグに直接書かれたスタイル)のみを取得する
const styleValue = box.style.backgroundColor;
box.style.backgroundColor のような element.style プロパティは、HTMLタグの style 属性に直接書き込まれたスタイル(インラインスタイル)しか取得できません。 そのため、今回のデモのようにCSSファイル側で指定されたスタイルを取得しようとしても、結果は「空っぽ」になってしまいます。
// インラインスタイルとして背景色を上書き(セット)する
box.style.backgroundColor = "#c72c4c";
値を「変更(セット)」する場合は element.style を使います。 セットするとインラインスタイルとしてHTMLに書き込まれるため、CSSファイルの記述よりも優先度が高くなり、見た目が変化します。
getComputedStyle() は「最終的な計算結果」を取得
// CSSファイルなども含め、最終的にブラウザが計算したスタイルを取得する
const computedStyle = window.getComputedStyle(box);
resultText.textContent = computedStyle.backgroundColor;
// ※取得される値は rgb(27, 180, 212) のような形式になります
一方、window.getComputedStyle(element) は、CSSファイル、インラインスタイル、ブラウザのデフォルトスタイルなど、すべての情報を合算して最終的に画面に適用されているスタイル(計算済みスタイル)を取得できます。 CSSファイルに書いた色やサイズをJavaScriptで取得したい場合は、必ずこちらを使用します。
【重要】getComputedStyle は「読み取り専用」
注意点として、getComputedStyle で取得したオブジェクトは読み取り専用(Read-only)です。 getComputedStyle(box).backgroundColor = "red"; のように値を書き換えようとするとエラーになります。
正しい使い分け
これまでの仕様を踏まえると、JavaScriptでのスタイルの扱いは以下のように使い分けます。
・スタイルの「取得」
現在の見た目(CSSファイルの指定含む)を知りたい場合は window.getComputedStyle() を使う。
・スタイルの「変更」
JSで新しくスタイルを当てたい場合は element.style を使う。
まとめ
今回は、JavaScriptでスタイルを扱う上で必ず知っておきたい getComputedStyle と element.style の違いについて解説しました。
JavaScriptを学び始めたばかりの頃は、「なぜかCSSの値が取れない…」と悩んでしまいがちなポイントですが、それぞれの「役割(インラインスタイル用か、計算済みスタイル用か)」をしっかり理解しておけば、もう迷うことはありません。
直接スタイルを操作・取得するこの基本テクニックも、しっかり使いこなしていきたいと思います!