Mayur
Mayur

Reputation: 289

color change Javascript

I am trying to

what I hv done- callin a javascript on tableRows id to change color,but it only changes the the color of 1st row.

<?php
  while($row_color_test = mysql_fetch_assoc($result_color_test))
  {
    ?>
      <tr id="tableRows">
        <td><?php echo $row_color_test['name'] ; ?></td>
        <td><?php echo $row_color_test['phone']; ?></td>
      </tr>
    <?php 
  }
    ?>

Javascript Function

function changecolor()
    {
     document.getElementById("tableRows").style.color="red";
    }

any idea why it happening although all the rows are dynamically created by while loop so all hv the same id and therefore,CSS rule sud apply on them.

Or is there a better way to do it??I hv to use Javascript only

Upvotes: 0

Views: 115

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

but it only changes the the color of 1st row.

Right. The tableRows id is on the row, and id values must be unique on the page. You can't have more than one element (row, in this case) with the same id. If you do, most browsers just ignore the id on subsequent elements on the page — so you're only seeing one element updated.

You could use a class instead:

<tr class="tableRows" ...

...and do this on most browsers:

var list = document.querySelectorAll(".tableRows");
var index;
for (index = 0; index < list.length; ++index) {
    ilst[index].style.color = "red";
}

But it would be better still to just set a class on the table and use CSS rules to turn the rows red instead.

document.getElementById("id_of_the_table").className += " foo";

...with this CSS:

.foo tr {
    color: "red"
}

Upvotes: 5

Related Questions