How to Get an Element's Width in Javascript

"Div" elements in a webpage are dynamic in that they automatically resize themselves upon publication. Getting the resulting size of such an element entails assigning that element an ID, pulling that element's properties from the document page, assigning the width property to a variable and then printing the value. This can all be accomplished by writing a single JavaScript function.

Instructions

    • 1

      Give the "div" element you are trying to analyze an ID:

      <div id="test_id">

    • 2

      Create a JavaScript function between the "head" tags of your webpage:

      <script type="text/javascript">
      function output_width()
      {

      }
      </script>

    • 3

      Obtain the properties of the "div" using the "document.getElementByID" method, and store the results in a variable:

      var div_properties = document.getElementByID("test_id");

      Place this between the function's {} tags.

    • 4

      Pull the width of the "div" from the variable with the "div" properties with the "style.width" method:

      div_width = div_properties.style.width;

      Place this after the "document.getElementByID" command.

    • 5

      Call the function from the body of your webpage by using the "document.write" method:

      <script type="text/javascript">
      document.write(output_width());
      </script>

      Place this between the "body" tags.

Related Searches:

References

Comments

Related Ads

Featured