Reputation: 25
I have a table that is generated with data from a .js file. What I want to do is be able to format rows ex. give them different color. I know you can add a class like <tr class="yellowrow"></tr>
but the way the code is I can't do it like that. I'm thinking a for loop might do.. any ideas?
<table id="data">
<thead>
<tr>
<th>Date</th>
<th>Amount</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<script type="text/javascript" src="js/people.js"></script>//file with information
<script type="text/javascript" >
for(var i=0; i<Name.length;i++){
document.write('<tr><td>' + date[i] + '</td><td>' + amount[i] + '</td><td>'
+Name[i]'</td></tr>');//this brings in the data to generate the rows
}
</script>
</tbody>
//so this gives me a table with a couple of rows... how can i format each row they
need to have different classes because they cant all have the same format.like one
can be blue, another red, another blue..ect.
Upvotes: 1
Views: 215
Reputation: 32921
Short answer: You can use CSS to style the different rows.
tr:nth-child(2n){
background-color: #ccc;
}
tr:nth-child(3n){
background-color: #444;
}
https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
Long, mostly unrelated answer: You shouldn't be using document.write
. You can add to the tbody a lot more elegantly like this.
<table id="data">
...
<tbody></tbody>
</table>
<script>
var rows = [];
for (var i=0; i<Name.length; i++){
rows.push(
'<tr>' +
'<td>' + date[i] + '</td>' +
'<td>' + amount[i] + '</td>' +
'<td>' + Name[i] + '</td>' +
'</tr>'
);
}
document.querySelector('#data tbody').innerHTML = rows.join('');
</script>
Why is document.write considered a "bad practice"?
Upvotes: 1
Reputation: 9583
if your just looking to alternate the colors you could just use a css selector like:
tr:nth-child(odd)
http://www.w3.org/Style/Examples/007/evenodd.en.html
Upvotes: 0