Tuesday, October 29, 2013

Several ways for dynamic style modification

In web development, you can have many ways to alter the style of the output in run-time, but they may have speed or manageable difference. Let's try using different ways to modify <td> background color.
The first way you may come out with you mind, maybe is the CSSStyleDeclaration object. Simply using element.style. It is straightforward but difficult to manage.
//pure javascript
var tds = document.getElementsByTagName('td');
for(var i = 0; i < tds.length; i++){
    tds[i].style.backgroundColor = 'grey';
}

//jQuery shorthand
$('td').each(function(i, el){
    el.style.backgroundColor = 'grey';
});

The second method is to play with the inline style attribute. Its very simlar with element.style except the style priority.
//pure javascript
var tds = document.getElementsByTagName('td');
for(var i = 0; i < tds.length; i++){
    tds[i].setAttribute('style', 'background-color:grey');
}

//jQuery shorthand
$('td').css('background-color', 'grey');

The third way I can think of is modifying the className. Actually it is quite hot, because it separate the JS ans CSS, it make the web site more manageable. And Object Oriented CSS is also rely on the className. And its performance is good, for example we don't need to loop through all <td> in our test case, we can directly add it to <table> or <body>.
.greyTD td{ background-color:grey }

//pure javascript
document.body.className += ' greyTD';

//jQuery shorthand
$(document.body).addClass('greyTD');

The final method I'd introduced is CSSStyleSheet, we dynamically create <style> and append it into the <head>. It performance is as good as modify the className, but it is more dynamic because no predefined CSS is needed. However, it is more difficult to manage and debug.
//pure javascript
var style = document.createElement('style');
style.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(style);

var sheet = style.sheet ? style.sheet : style.styleSheet;
var rules = sheet.cssRules ? sheet.cssRules : sheet.rules;
var index = rules.length;
if(sheet.insertRule){ // Standard browser
    sheet.insertRule('td{ background-color:grey }', index);
}else if(sheet.addRule){ // IE8 or below
    sheet.addRule('td', 'background-color:grey', index);
}

No comments:

Post a Comment