www.webdeveloper.com
Results 1 to 4 of 4

Thread: Novice Question: Return an attribute that is a number

  1. #1
    Join Date
    Apr 2013
    Posts
    5

    Novice Question: Return an attribute that is a number

    I've been trying to make the button respond with the height of the div (500). Can anyone help.

    <style>
    #stuff {
    height:500px;
    color:#39C;
    width:200px;
    }
    </style>
    <script language="JavaScript">
    function getHeight(){
    var thisDiv = document.getElementById("stuff");
    var thisHeight = thisDiv.getAttribute("height");
    alert(thisHeight);
    }
    </script>

    <div id="stuff" title="This is the stuff ID's title">
    <h1>Get Attribute Example</h1>
    <p>Rose India Technologies Pvt. Ltd. is a global services company.</p>
    <input type="button" value=" Get Height " onclick="getHeight();">
    </div>

    Thanks!

  2. #2
    Join Date
    Dec 2012
    Posts
    136
    The div doesn't have a height attribute on it so "getAttribute('height')" won't work in this instance.

    You could change the getHeight function to something like this to get the height of the div

    HTML Code:
    function getHeight(){
        var thisDiv = document.getElementById("stuff");
        var style = window.getComputedStyle(thisDiv);
        var thisHeight = parseInt(style.height);
        alert(thisHeight);
    }

  3. #3
    Join Date
    Mar 2009
    Posts
    512
    You can determine the height of an element by using the "offsetHeight" property of the element, as in :

    Code:
    function getHeight(elementId){
      var x = document.getElementById(elementId);
      return x.offsetHeight;
    }
    Its that simple, and its cross-browser safe. The value it returns is the height of the element in pixels.

  4. #4
    Join Date
    Dec 2012
    Posts
    136
    Remember though that offsetHeight returns the full height of the element, including any padding, using the getComputedStyle method gives you the value you've set the height at.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles