By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,397 Members | 1,374 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,397 IT Pros & Developers. It's quick & easy.

get div padding

100+
P: 111
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,
May 15 '08 #1
Share this Question
Share on Google+
1 Reply


100+
P: 428
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. }
  22.  
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'));
May 15 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.