22
21

More than 5 years have passed since last update.

DOM 要素の実際に使用されているスタイルを取得

Posted at

element.style から取得できるのは JavaScript で動的に設定したスタイルだけですが、window.getComputedStyle() を使うと親要素からの継承なども含めて DOM 要素の実際に使用されているスタイルを確認することができます。

var styles = getComputedStyle(document.body);
console.log(styles.marginTop);
// 0px

:before, :after など疑似要素のスタイルを知りたい場合は第二引数を使います。

var styles = getComputedStyle(document.body, ':before');

これまで jQuery ばかり使っていたので、DOM の API は知らないことばかりですね・・・。

22
21
0

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
22
21