SetStyleByClass function
6
This function sets a particular style for an element based on it's class
function setStyleByClass(objClass,objProperty,objValue){
// This function will apply a style to an Element based on Class
// Works with IE and Mozilla based browsers
// 2005-10-25: Jeremy Edmiston
var elements = (ie) ? document.all : document.getElementsByTagName('*')
for(var i = 0; i < elements.length; i++){
if(elements[i].className == objClass) {
//eval('elements[i].style.' + objProperty + " = '" + objValue + "'");
elements[i].style[objProperty] = objValue;
}
}
}






For instance I set rows in a table with a particular class. I then use DOM to find all elements by class, append an onMouseClick event to them and in the onMouseClickI call a function that will expand the row and drill down on data that can be dynamically loaded as well.
Like stated above, there are some uses...
// setStyleByClass: given an element type and a class selector,
// style property and value, apply the style.
// args:
// t - type of tag to check for (e.g., SPAN)
// c - class name
// p - CSS property
// v - value
var ie = (document.all) ? true : false;
function setStyleByClass(t,c,p,v){
var elements;
if(t == '*') {
// '*' not supported by IE/Win 5.5 and below
elements = (ie) ? document.all : document.getElementsByTagName('*');
} else {
elements = document.getElementsByTagName(t);
}
for(var i = 0; i < elements.length; i++){
var node = elements.item(i);
for(var j = 0; j < node.attributes.length; j++) {
if(node.attributes.item(j).nodeName == 'class') {
if(node.attributes.item(j).nodeValue == c) {
eval('node.style.' + p + " = '" + v + "'");
}
}
}
}
}
<style> .korisu-test { background-color: pink; } </style> <div class="korisu-test">testing some layout stuff here</div> <style> .korisu-test { border: 3px dotted blue; } </style>and it's evaluated here (!important added to override site's style):But yes, it is better to define all your styles in the CSS stylesheet rather then litter your HTML with them