Thomas
Thomas

Reputation: 355

How to change dynamically tabe cell text colors?

I need a solution to change dynamically via javascript the text color of table cells. The text can be the following colors: blue, green, red and black.

Table example:

<html>
  <head>
    <title></title>
    <meta http-equiv="content-type" content="text/html; charset="UTF-8">
    <script src="jquery-mobile/jquery-1.6.4.min.js"       type="text/javascript"></script>
    <script src="jquery-mobile/jquery.mobile-1.0.min.js"  type="text/javascript"></script>
  </head>
  <body>
  <div data-role="page" id="page">
    <div data-role="content">
      <table width="100%" border="0" id="friends" class="menu">
        <tr id="friend1">
          <td>First name</td>
          <td>Surname</td>
        </tr>
        <tr id="friend2">
          <td>First name</td>
          <td>Surname</td>
        </tr>
        <tr id="friend3">
          <td>First name</td>
          <td>Surname</td>
        </tr>
        <tr id="friend4">
          <td>First name</td>
          <td>Surname</td>
        </tr>
        <tr id="friend5">
          <td>First name</td>
          <td>Surname</td>
        </tr>
      </table>
    </div>
  </div>
  </body>
</html>

How can I change the text color? Conditions are, that I could do this dynamically via javascript and more than one time. That means I need to set a color (e.g. red), later reset the color to black and set it following to another color (e.g. blue).

I saw some examples with setting the color via id, but I found no way to transfer this example to table cells and each cell could have different colors.

Can someone help me?

Upvotes: 2

Views: 27487

Answers (2)

Th0rndike
Th0rndike

Reputation: 3436

create a class for each color in your css file:

.redCell{
    color:red;
}
.blueCell{
    color:blue;
}
.yellowCell...

then, add the class to the TD you need:

$('#friend01').addClass('blueCell');

if you need to remove the color:

$('#friend01').removeClass('blueCell');

if you need to know if a cell has a certain color:

$('#friend01').hasClass('blueCell');

Upvotes: 3

Mic
Mic

Reputation: 523

you can go through all td's

var tds = document.getElementsByTagName("td");

for(var i = 0, j = tds.length; i < j; ++i)
   tds[i].style.color = "#00AA00";

OR

you can go through td's that are childs of a special element:

var myNode = document.getElementById("friend2");
var tds = myNode.getElementsByTagName("td");

    for(var i = 0, j = tds.length; i < j; ++i)
       tds[i].style.color = "#00AA00";

greetings!

Upvotes: 7

Related Questions