get div padding

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nitinpatel1117
    New Member
    • Jun 2007
    • 111

    get div padding

    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.)


    Code:
    var content_pTop = document.getElementById('my_div').style.paddingTop;
    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
    Contributor
    • Jun 2006
    • 428

    #2
    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.getEle mentById('div_1 ').style.paddin g= '1em 1em 1em 1em'


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

    Code:
    document.deepCss= function(who, css){
    	var val= '', str= '';
    	if(!who || who.style== undefined) return '';
    	if(/\-/.test(css)){
    		str= css.replace(/\-[a-z]/g, function(w){
    			return w.charAt(1).toUpperCase() + w.substring(2);
    		})
    	}
    	val= who.style[str];
    	if(!val){
    		if(who.currentStyle) val= who.currentStyle[str];
    		else{
    			var dv= document.defaultView || window;
    			if(dv && dv.getComputedStyle){
    				str= str.dasher(true);
    				val= dv.getComputedStyle(who,'').getPropertyValue(css);
    			}
    		}
    	}
    	return (val)? val: '';
    }
    Pass the method an element reference and a css property value-
    Shortcut families(font,b ackground,margi n,border,paddin g) can return odd values, it's best to get a specific value(padding-top)

    var who=document.ge tElementById('d iv_1')
    alert(document. deepCss(who,'pa dding-top'));

    Comment

    Working...