0

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.

0

1 Answer 1

2

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';
};
Sign up to request clarification or add additional context in comments.

3 Comments

Important to note is that CSS properties with dashes -, like background-color, have to be written camle-cased, like backgroundColor.
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
Thanks, this solved my problem for now. But at the same time raised few queries in my mind. 1 - Isn't that possible putting javascript values as javascript entity inside html tag attribute, I mean the way I wished. 2 - Can you suggest me some good resource on net where I can read and understand DOM & its level 1, 2 and 3. DOM features compatibility with browser's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.