style プロパティを使うと、JavaScript から直接 CSS スタイルを変更できます。要素のインラインスタイルを操作するときに使います。
基本的な使い方
const element = document.getElementById('box'); // スタイルを設定 element.style.color = 'red'; element.style.backgroundColor = '#f0f0f0'; element.style.fontSize = '20px';
CSS プロパティ名の変換
CSS のハイフン区切りは、JavaScript ではキャメルケースになります。
| CSS | JavaScript |
|---|---|
| background-color | backgroundColor |
| font-size | fontSize |
| margin-top | marginTop |
| border-radius | borderRadius |
| z-index | zIndex |
スタイルを取得する
const element = document.getElementById('box'); // インラインスタイルを取得 console.log(element.style.color); // 注意:CSS ファイルで設定したスタイルは取得できない // インラインスタイルのみ取得可能
CSS ファイルで設定されたスタイルを取得するには getComputedStyle を使います。
スタイルを削除する
空文字を設定するとスタイルが削除されます。
element.style.color = ''; // color スタイルを削除
実際に動かしてみよう
HTML
CSS
JavaScript
<div id="box">ボックス</div> <button id="redBtn">赤くする</button> <button id="blueBtn">青くする</button> <button id="bigBtn">大きくする</button> <button id="resetBtn">リセット</button>
#box { padding: 20px; background: #eee; transition: all 0.3s; }
const box = document.getElementById('box'); document.getElementById('redBtn').addEventListener('click', () => { box.style.color = 'white'; box.style.backgroundColor = 'red'; }); document.getElementById('blueBtn').addEventListener('click', () => { box.style.color = 'white'; box.style.backgroundColor = 'blue'; }); document.getElementById('bigBtn').addEventListener('click', () => { box.style.fontSize = '24px'; box.style.padding = '40px'; }); document.getElementById('resetBtn').addEventListener('click', () => { box.style.color = ''; box.style.backgroundColor = ''; box.style.fontSize = ''; box.style.padding = ''; });
複数のスタイルを一度に設定
cssText を使うと、複数のスタイルを一度に設定できます。
element.style.cssText = 'color: red; font-size: 20px; margin: 10px;';
ただし、既存のインラインスタイルは上書きされます。
style vs classList
style プロパティ
動的に値を変えたいとき(アニメーション、ユーザー入力に応じた変更)
classList
定義済みのスタイルを切り替えたいとき。保守性が高い
基本的には CSS クラスを切り替える方法がおすすめです。style プロパティは、値を動的に計算する必要があるときに使いましょう。
// 推奨:クラスを切り替える element.classList.add('active'); // style が必要なケース:動的な値 element.style.left = mouseX + 'px'; element.style.top = mouseY + 'px';