Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New to the CF scene
    Join Date
    Dec 2012
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Is this possible: document.+variable+.style.+variable?

    Hi,

    Is it possible to have something like the following?

    Code:
    document.VARIABLE1.style.VARIABLE2 = (some color);
    Thanks for any ideas.

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,773
    Thanks
    55
    Thanked 518 Times in 515 Posts
    you can replace the dots with square brackets:
    Code:
    <script>
    var el="body";
    var prop="backgroundColor";
    var col="red";
    document[el].style[prop]=col;
    </script>
    although it's probably more useful to give your elements IDs and reference them that way:
    Code:
    <style>
    #thediv{
    height:200px;
    width:200px;
    border:solid;
    }
    </style>
    </head>
    <body>
    <div id="thediv"></div>
    <script>
    var el="thediv";
    var prop="backgroundColor";
    var col="red";
    document.getElementById(el).style[prop]=col;
    </script>
    </body>
    if you have alot of properties you want to change you can make an object and loop through that:
    Code:
    <style>
    #thediv{
    height:200px;
    width:200px;
    border:solid;
    }
    </style>
    </head>
    <body>
    <div id="thediv"></div>
    <script>
    var el="thediv";
    var mystyle={backgroundColor:"red", width:"400px"};
    for (i in mystyle){
    document.getElementById(el).style[i]=mystyle[i];
    }
    </script>
    </body>
    or you can use .cssText and make strings out of the style combinations you want:
    Code:
    <style>
    #thediv{
    height:200px;
    width:200px;
    border:solid;
    }
    </style>
    </head>
    <body>
    <div id="thediv"></div>
    <script>
    var el="thediv";
    var mystyle="background-color:red; width:400px";
    document.getElementById(el).style.cssText=mystyle;
    </script>
    </body>


  •  

    Posting Permissions

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