要素の幅と高さを取得 - Javascript

  • 作成日:
  • 最終更新日:2025/10/07

clientWidth clientHeight

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8" />
  <title>sample</title>
  <script src="script.js"></script>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div id="box"></div>
</body>
</html>

style.css

#box {
  width: 100px;
  height: 100px;
  background-color: gray;
}

script.js

window.onload = function(){
  const box = document.getElementById('box');
  console.log("width:" + box.clientWidth);
  console.log("height:" + box.clientHeight);
}

padding、border、scroll を指定していた場合、padding のみを含めた値を取得します。