I’m making a webpage which used to have % widths for my divs, but these would display too erratically in different browsers, so I had to switch to static widths. I got the idea though to recalculate the widths based on the pane width on resize and this works nice. I’m debating though, whether it is better to change the styles for my properties via the stylesheet collection, or via the DOM. Here are the two scripts:
Stylesheet Collection
[code=php]function switchTableSize(width, height)
{
if (typeof document.styleSheets != “undefined”) {
var styleSheet = document.styleSheets[1];
var rules = null;
var chemWidth = Math.floor((width-72)/18);
if (typeof styleSheet.rules != “undefined”)
rules = styleSheet.rules;
else
rules = styleSheet.cssRules;
for (var i = 0; i < rules.length; i++) {
switch (rules[i].selectorText)
{
case “#container”:
rules[i].style.width = width + “px”;
break;
case “.element”:
rules[i].style.width = chemWidth + “px”;
break;
case “.spacer”:
rules[i].style.width = chemWidth*3 + 12 + “px”;
break;
default:
break;
}
}
}
}
DOM
[code=php]function switchTableSize(width, height)
{
var chemWidth = Math.floor((width-72)/18);
document.getElementById(‘container’).style.width = width + ‘px’;
var divs = document.getElementsByTagName(‘div’);
for (var i = 0; i < divs.length; i++) {
var div = divs[i]
if (div.className && (‘ ‘ + div.className + ‘ ‘).indexOf(‘ element ‘) != -1) {
div.style.width = chemWidth + ‘px’;
} else if (div.className && (‘ ‘ + div.className + ‘ ‘).indexOf(‘ spacer ‘) != -1) {
div.style.width = chemWidth*3 + 12 + ‘px’;
}
}
}
On one hand, the DOM version is shorter (in code) and works with more browsers. However, there are about 175 divs in my page, 150 of which fall under the ‘element’ className, and 2 which fall under the ‘spacer’ className, (not to mention I’m using an indexOf call) so it seems like it might be resource intensive.
On the other hand, the stylesheet collection version seems more elegant, only changes 3 properties (and the CSS page in question has 10 properties total). However there is slightly less browser support for this method.
Any thoughts on this?