javascriptgetelementsbyname

JavaScript: getElementById does not return the width of a button


Why does the alert window not show the button's width here? I looked through similar questions, but it looks like my question is too simple to have an answer there.

<!DOCTYPE html>
<html>
<body>

<button id="jock" onclick="myFunction()">Try it</button>

    <script>
    function myFunction() 
       {
       alert(document.getElementById("jock").style.width);
       }
    </script>

    </body>
    </html>

Solution

  • Use offsetWidth instead of style width. This will get the elements true width value.

    <!DOCTYPE html>
    <html>
    <body>
    
      <button id="jock" onclick="myFunction()">Try it</button>
    
      <script>
        function myFunction() {
          alert(document.getElementById("jock").offsetWidth);
        }
      </script>
    
    </body>
    </html>