Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dynamically modify css classes

Status
Not open for further replies.

shades44

Programmer
Jun 14, 2004
25
CA
hi,

does anyone know of a way to modify a css classes' properties using javascript such as this simple style:

<style>
.highlightedCell
{
BACKGROUND-COLOR: RED;
}
</style>

lets say i have some cells in a datagrid that have this class and then i want to change their background color to blue, can i do that by changing the BACKGROUND-COLOR property of the class itself using javascript?
 
I don't think there's an easy way...
This iterates through all children of a certain element, then all their children, etc. and sets the background of each one with class hilightedCell to the given color.
Code:
function setBackground(elem, color)
{
  var children = elem.childNodes;
  for (var i=0; i<children.length; i++)
  {
    if (children[i].className.indexOf("hilightedCell") > -1)
      children[i].style.backgroundColor = color;
    if (children[i].childNodes.length > 0)
      setBackground(children[i], color);
  }
}

--Chessbot

"Violence is the last refuge of the incompetent." -- Asimov, Foundation
 
i guess the only reason i want to directly alter the class is so i dont have to iterate through all the elements that inherit properties from that class..

im still hopeful of a way
 
Why not give them all the same name? Then you can use
Code:
function changeColor(name, color)
{
  var elems = document.getElementByName(name);
  if (!elems)
    return;
  if (!elems.length)
  {
    elems.style.backgroundColor = color;
    return;
  }
  for (var i=0, i<elems.length; i++)
    elems[i].style.backgroundColor = color;
}
This should work.

--Chessbot

"Violence is the last refuge of the incompetent." -- Asimov, Foundation
 
well that is a solution.. but im still iterating. I thought maybe i could alter the property directly in the class from which all those elements get their style and then they would all somehow all be modified.. but i guess it doesnt work that way. Am i right? In any way im going to have to call the style on each particular element and change it (iteration).
 
I don't think that a CSS is part of the DOM of either major browser. You can modify the style properties of individual elements... but CSS tags aren't elements in and of themselves.

If I'm wrong, please correct me! I'd like to be wrong, in this case.

Thomas D. Greer

Providing PostScript & PDF
Training, Development & Consulting
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top