[SOLVED] how to document.getElementById().style.padding-left ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jmatos
    New Member
    • Mar 2008
    • 1

    [SOLVED] how to document.getElementById().style.padding-left ?

    I need to change the style of an element changing its padding-left property (got it in firefox but IE is a different battle..). I can use document.getEle mentById().styl e.XX
    to everything i need, except with padding-left, as it is separated by a ' - ' and it is not correct to use it as it was supposed to:

    document.getEle mentById('el'). style.padding-left = '5px'

    will throw 'invalid assignment left-hand side', as expected..

    Any help please?

    [SOLVED]

    Apparently the property turns into paddingLeft (or paddingTop, paddingBottom, paddingRight) so it can be used as expected:

    document.getEle mentById('el'). style.paddingLe ft = '5px'
    document.getEle mentById('el'). style.paddingTo p = '5px'
    document.getEle mentById('el'). style.paddingRi ght = '5px'
    document.getEle mentById('el'). style.paddingBo ttom = '5px'
  • hsriat
    Recognized Expert Top Contributor
    • Jan 2008
    • 1653

    #2
    Originally posted by jmatos
    I need to change the style of an element changing its padding-left property (got it in firefox but IE is a different battle..). I can use document.getEle mentById().styl e.XX
    to everything i need, except with padding-left, as it is separated by a ' - ' and it is not correct to use it as it was supposed to:

    document.getEle mentById('el'). style.padding-left = '5px'

    will throw 'invalid assignment left-hand side', as expected..

    Any help please?
    For that use paddingLeft.

    In general, anything of style containing a hyphen ( - ) will work for JavaScript when hyphen is removed and first letter of the second word is made capital.

    eg.
    background-image -> backgroundImage
    border-top -> borderTop


    [EDIT]
    Glad to know you solved it.

    Comment

    • mrhoo
      Contributor
      • Jun 2006
      • 428

      #3
      Converting between css syntax('border-top-width') and javascript property names ('borderTopWidt h') is a common webpage chore.
      The values you are working with are always strings, so a String method to do the conversion may be appropriate:

      [CODE=javascript]

      String.prototyp e.dash= function(boo){
      var s= this;
      if(/^[A-Z]+$/.test(s) || /\-/.test(s)) s = s.toLowerCase() ;
      if(boo=== true ){
      if(/[a-z][A-Z]/.test(s)){
      s= s.replace(/[A-Z]/g, function(w){
      return "-" + w.toLowerCase() ;
      })
      }
      }
      else if(/\-/.test(s)){
      s= s.replace(/\-[a-z]/g, function(w){
      return w.charAt(1).toU pperCase() + w.substring(2);
      })
      }
      return s;
      }
      [/CODE]

      // pass the argument 'true' for css (hyphen-ated) , leave it out or pass 'false' to return camelCase.

      Comment

      Working...