Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8764

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

$
0
0

プログラミング勉強日記

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

取得したいこと

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

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

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ファイルで先に背景色を変える指定を行い、取得する必要があると分かりました。

参考資料


Viewing all articles
Browse latest Browse all 8764

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>