Setting DIV width and height in JavaScript

The properties you’re using may not work in Firefox, Chrome, and other non-IE browsers. To make this work in all browsers, I also suggest adding the following:

document.getElementById('div_register').setAttribute("style","width:500px");

For cross-compatibility, you will still need to use the property. Order may also matter. For instance, in my code, when setting style properties with JavaScript, I set the style attribute first, then I set the properties:

document.getElementById("mydiv").setAttribute("style","display:block;cursor:pointer;cursor:hand;");
document.getElementById("mydiv").style.display = "block";
document.getElementById("mydiv").style.cursor = "hand";

Thus, the most cross-browser compatible example for you would be:

document.getElementById('div_register').setAttribute("style","display:block;width:500px");
document.getElementById('div_register').style.width="500px";

I also want to point out that a much easier method of managing styles is to use a CSS class selector and put your styles in external CSS files. Not only will your code be much more maintainable, but you’ll actually make friends with your Web designers!

document.getElementById("div_register").setAttribute("class","wide");

.wide {
    display:block;
    width:500px;
}

.hide {
    display:none;
}

.narrow {
    display:block;
    width:100px;
}

Now, I can easily just add and remove a class attribute, one single property, instead of calling multiple properties. In addition, when your Web designer wants to change the definition of what it means to be wide, he or she does not need to go poking around in your beautifully maintained JavaScript code. Your JavaScript code remains untouched, yet the theme of your application can be easily customized.

This technique follows the rule of separating your content (HTML) from your behavior (JavaScript), and your presentation (CSS).

Leave a Comment