views:

54

answers:

1

Hi,

I have created some div(s) on a page. Depending on the browser (or may be any other settings) I want to change the width of these div(s).

Now, if I embed style=" blah blah blah...; width:200px" inside div tag, its ok. But I want this 200px to be, say, 220 sometime or 230 or 240 other times. So what I want now to calculate my required width in javascript, put it in a variable and then insert it as width property value like in &{}...

If I am clear is this possible in this manner, if yes how.

+3  A: 

You can set CSS properties on DOM elements in JavaScript:

Say you had a div with an id of someDiv, you could use the following JavaScript to change its width:

window.onload = function() {
   var newWidth = 220;
   document.getElementById('someDiv').style.width = newWidth + 'px';
};
Jacob Relkin
Important to note is that CSS properties with dashes `-`, like `background-color`, have to be written camle-cased, like `backgroundColor`.
Felix Kling
ok right. But this way if I call getElementById before the page is loaded, ie the <body> is complete, is gives error Error: document.getElementById("someDiv") is null
Rahul Utb
@Rahul, I updated my answer. Try it out now.
Jacob Relkin
Rahul Utb