プログラミング勉強日記
2020年11月15日
ドットインストールでJavaScriptを学習中にふと、『CSSのスタイルはどうやって取得するのか?』と気になりました。
自分的には、ややこしかったので今後間違えないように記録していきます。
取得したいこと
- CSSファイルに記述したbackgroundプロパティの値を取得したいと思います。
index.html
<divclass="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
<divclass="box"id="target"style='background: pink;'></div>
と要素にstyle属性を直接指定する
もしくは、
script.js
$target.style.background='pink';console.log($target.style.background);
とjsファイルで先に背景色を変える指定を行い、
取得する必要があると分かりました。