LoginSignup
24
23

div タグのスタイルを参照しようとしたら参照できなかった話

Posted at

例えば、次のような HTML と CSS があったときに、

hoge.html
<div id="hoge"></div>
hoge.css
#hoge {
  display: flex;
}

以下のコードでコンソールに出力されたのは "flex" ではなく空文字だったという話です。

hoge.js
const divElement = document.getElementById("hoge");
console.log(divElement.style.display); // 空文字が出力される

解決方法

上記のコードで言うと divElement.style.xxxx で参照できるのは JavaScript で動的に設定したスタイルとなるため、CSS で適用したスタイルを参照する場合は window.getComputedStyle() を使用します。

これで、DOM 要素の実際に適用されているスタイル(計算されたスタイル)を参照することができます。

const divElement = document.getElementById("hoge");
const computedStyle = window.getComputedStyle(divElement);
console.log(computedStyle.display); // flex

ちなみに、width: 50%; などが適用されている場合は計算後の具体的な数値を参照することができます。

#hoge {
  width: 50%;
  color: red;
}
const divElement = document.getElementById("hoge");
const computedStyle = window.getComputedStyle(divElement);
console.log(computedStyle.width); // 425px
console.log(computedStyle.color); // rgb(255, 0, 0)

今まで馴染みのなかった window.getComputedStyle() ですが、スタイルを当て過ぎて「結局、今、どうなってるの?」を知りたいときには便利かも知れません。

24
23
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
23