【JavaScript】html要素の基準フォントサイズを取得する


html要素の基準フォントサイズ取得

WEBサイトのレスポンシブル対応などで、html要素の基準フォントサイズが知りたくなったときにそれを取得することがあったのでメモ。


let root = document.documentElement; //htmlのルート要素を取得
let style = window.getComputedStyle(root).getPropertyValue('font-size'); //ルート要素のcssプロパティを全て取得し、その中からフォントサイズを取得
let stFontSize = parseFloat(style); //float型の数値に変換

window.getComputedStyleでcssプロパティを取得

let style = window.getComputedStyle(root).getPropertyValue('font-size');

この部分がポイントで、 window.getComputedStyle()の引数に入れたelementのcssプロパティを全て返してくれます。
https://developer.mozilla.org/ja/docs/Web/API/Window/getComputedStyle

なので、基準フォントサイズに限らず、引数を変えれば好きなelementのcssプロパティを取得出来ます。