View Single Post
Old 12-25-2012, 04:07 PM   PM User | #2
xelawho
Senior Coder

 
xelawho's Avatar
 
Join Date: Nov 2010
Posts: 2,437
Thanks: 52
Thanked 454 Times in 452 Posts
xelawho will become famous soon enoughxelawho will become famous soon enough
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>
xelawho is offline   Reply With Quote