24
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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

Last updated at Posted at 2024-03-21

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

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

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

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

解説

一部修正しました
本稿をご覧になられた方からご指摘を頂きましたので、一部修正いたしました。

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

HTMLElement.styleプロパティは、HTML 要素の「インラインスタイル」(style 属性で指定したスタイル)のみを参照するため、CSSファイルや<style>タグで定義されたスタイルは反映されません。

上記のコードで空文字が表示されたのは、<div id="hoge"></div>に style 属性でdisplayプロパティを設定していないためです。

よって、style 属性でdisplayプロパティを設定すれば"flex"が出力されます。

html
<div id="hoge" style="display: flex;"></div>
js
const divElement = document.getElementById("hoge");
console.log(divElement.style.display); // "flex"

CSS や <style>タグで定義されたスタイルを含め、ブラウザが実際に要素に適用しているスタイル(計算されたスタイル)を参照する場合はwindow.getComputedStyle()を使います。

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

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

css
#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
24
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
24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?