要素の幅と高さを取得する

要素の幅と高さを取得するには、要素のoffsetWidthプロパティとoffsetHeightプロパティを使用します。

const box = document.querySelector('.box');

const width = box.offsetWidth,
    height = box.offsetHeight;Code language: JavaScript (javascript)

offsetWidthoffsetHeightには、パディングとボーダーが含まれます。

ボーダーを含まない要素の幅と高さを取得するには、clientWidthプロパティとclientHeightプロパティを使用します。

const box = document.querySelector('.box');

const width = box.clientWidth,
    height = box.clientHeight;Code language: JavaScript (javascript)

clientWidthプロパティとclientHeightプロパティには、パディングも含まれることに注意してください。

このチュートリアルは役に立ちましたか?