1
0

More than 3 years have passed since last update.

【JavaScript】要素に指定したCSSスタイルを取得したい!

Last updated at Posted at 2020-11-15

プログラミング勉強日記

2020年11月15日
ドットインストールでJavaScriptを学習中にふと、『CSSのスタイルはどうやって取得するのか?』と気になりました。
自分的には、ややこしかったので今後間違えないように記録していきます。

取得したいこと

  • CSSファイルに記述したbackgroundプロパティの値を取得したいと思います。

スクリーンショット 2020-11-15 8.37.08.jpg

index.html
  <div class="box" id="target"></div>
style.css
.box {
    width: 100px;
    height: 100px;
    background-color: rgb(204,204,204);
}

完成コード

まず最終的に取得できたコードが以下になります。

script.js

'use strict';
let $target = document.getElementById('target');
console.log(window.getComputedStyle($target)['background']);

完成コードの解説

1.id属性が'target'の要素を取得。

2.window.getComputedStyle($target)[background]で取得した要素のCSSStyleDeclarationオブジェクトのbackgroundプロパティの値を返す。

つまづいた箇所

ドットインストールで、boxクラスの背景色を変える際に、

script.js
$target.style.background = 'pink';

と記述していたので、背景色を取得する時も、

script.js
console.log($target.style.background);

でいけるかと思ったのですが、コンソール見てみると何も取得できていませんでした。

もし、上記の書き方で取得する際は、

index.html
  <div class="box" id="target" style='background: pink;'></div>

要素にstyle属性を直接指定するもしくは、

script.js
$target.style.background = 'pink';
console.log($target.style.background);

jsファイルで先に背景色を変える指定を行い、取得する必要があると分かりました。

参考資料

1
0
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
1
0