▲TOPへ戻る

【javascript】スタイルシートのCSSを取得する方法 getComputedStyle getPropertyValue

getPropertyValue

要素.style.プロパティ名 = 値(value);

HTMLに直接styleが書き込まれていれば、、、

  <div class="box" style="background: black;">
    <div class="text">テキスト</div>
  </div>

以下のように、取得できます。

  const box = document.querySelector(".box");
  console.log(box.style.background)
  //  結果  =>  black

参考

js
【javascript】CSSを追加、削除、変更する方法

HTML内に書かれていない場合

  <div class="box">
    <div class="text">テキスト</div>
  </div>

先ほどの、
要素.style.プロパティ名 = 値(value;
では、何も取得できません。

getComputedStyle

まずは、getComputedStyleで全体を取得。

  const box = document.querySelector(".box");
  let boxStyle = window.getComputedStyle(box);
  console.log(boxStyle); 
cssStyleDeclaration

getPropertyValue

取得したいプロパティ名を指定します。

  const box = document.querySelector(".box");
  let boxStyle = window.getComputedStyle(box);
  console.log('boxStyle.getPropertyValue("background") : ',
    boxStyle.getPropertyValue("background"));

取得できました。

getPropertyValue

bodyのstyleを取得したい時

  const bodyStyle = window.getComputedStyle(document.body);
  const bodyStyleBackground = bodyStyle.getPropertyValue("background");
  console.log(bodyStyleBackground);

if文で分岐させる

テキスト
    btn.addEventListener("click", ()=>{
    //  スタイルシートがrgb(51, 51, 51)で、かつ、HTMLにCSSが追加されていない時の処理
    if (boxStyleBackground == "rgb(51, 51, 51)" && box.style.backgroundColor == "") {
      text.style.color = "#333"  //  文字が黒に
      box.style.background = "#fff";  //  背景が白に
      box.style.border = "1px solid #333"  
    } else{
      text.style.color = "#fff"  //  文字が白に 
      box.style.background = "";  //  HTMLのCSSを消去 → 背景が黒
      box.style.border = ""
    }
  })
point

要素.style.プロパティ名 = 値(value);
=> HTMLに書かれたCSSを取得

getComputedStyle
=> スタイルシートのCSSを取得

getPropertyValue
=> getPropertyValueで取得したものの中から必要なプロパティを指定し、取得

こんな記事も読まれています。

profile

パソコン好きなガオ

コロナ禍によるステイホームを機にプログラミングを学ぶ。パソコンに関してはプロではないが、ちょっと詳しい程度。

パソコン

javascript

カメラ

ブログ