Sign In | Register Now About Bytes | Help | Site Map
Connecting Tech Pros Worldwide

get div padding

Question posted by: nitinpatel1117 (Member) on May 15th, 2008 11:38 AM
Hi

I have a HTML div element that has CSS padding applied to it.

I am trying to retrieve the top and bottom padding values that are on this div.

I have tried the following JavaScript code to try to get the top padding, but it does not seem to work. (Also this code does not produce any errors.)


Expand|Select|Wrap|Line Numbers
  1. var content_pTop = document.getElementById('my_div').style.paddingTop  ;
  2. alert (content_pTop);


does anyone know what i am doing wrong, or know of a way to get the padding values of any given div.

thanks,
mrhoo's Avatar
mrhoo
Needs Regular Fix
408 Posts
May 15th, 2008
01:04 PM
#2

Re: get div padding
You can only read a style property of an element if it is set inline.

<div id="div_1" style="padding:1em 1em 1em 1em">
or in a script-
document.getElementById('div_1').style.padding= '1em 1em 1em 1em'


You can access the css inheritance chain,
but it requires a crossbrowser method :

Expand|Select|Wrap|Line Numbers
  1. document.deepCss= function(who, css){
  2.     var val= '', str= '';
  3.     if(!who || who.style== undefined) return '';
  4.     if(/\-/.test(css)){
  5.         str= css.replace(/\-[a-z]/g, function(w){
  6.             return w.charAt(1).toUpperCase() + w.substring(2);
  7.         })
  8.     }
  9.     val= who.style[str];
  10.     if(!val){
  11.         if(who.currentStyle) val= who.currentStyle[str];
  12.         else{
  13.             var dv= document.defaultView || window;
  14.             if(dv && dv.getComputedStyle){
  15.                 str= str.dasher(true);
  16.                 val= dv.getComputedStyle(who,'').getPropertyValue(css);  
  17.             }
  18.         }
  19.     }
  20.     return (val)? val: '';
  21. }


Pass the method an element reference and a css property value-
Shortcut families(font,background,margin,border,padding) can return odd values, it's best to get a specific value(padding-top)

var who=document.getElementById('div_1')
alert(document.deepCss(who,'padding-top'));

Reply
Reply
Not the answer you were looking for? Post your question . . .
189,872 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).

Latest Articles: Read & Comment
Top Javascript / DHTML / Ajax Forum Contributors