I tried to change the color of the first td element in each row to red.
HTML:
<table id="test">
<tr>
<td>test1</td>
<td>test2</td>
</tr>
<tr>
<td>test3</td>
<td>test4</td>
</tr>
</table>
I tried this JS:
var tr = document.getElementsByTagName('tr');
tr.firstChild.style.color = 'red';
No Jquery please.
Use rows and cells to access the rows and columns of the table. See below code,
var table = document.getElementById('test');
for (var i = 0; i < table.rows.length; i++) {
var firstCol = table.rows[i].cells[0]; //first column
firstCol.style.color = 'red'; // or anything you want to do with first col
}
DEMO: http://jsfiddle.net/QNEyx/
Parsing with JS could be costly, if you are fine achieving the same with the CSS, then here you go.
#test tr td:nth-of-type(1) {
color: red;
}
Or
#test tr td:first-child {
color: red;
}
As said in another reply, css is the natural way to accomplish this.
As you are stuck with js, you can use js to inject a stylesheet in your page:
var styleNode=document.createElement("style");
document.head.appendChild(styleNode);
var cssString="#test tr td:first-child {color: red;}";
if (styleNode.styleSheet) { // IE
styleNode.styleSheet.cssText = cssString;
}
else {
styleNode.appendChild(document.createTextNode(cssString));
}
The benefit of using a stylesheet is that you avoid race conditions (case when the table is built dynamically).
Related
I have an html table and I want to color the rows based on the value in the first column of that row. If the value is "CONFIRMED" I want to color the row green, and if it is "UNCONFIRMED" I want to color the row red.
The JS I am using to do this is:
$(function(){
$("tr").each(function(){
var col_val = $(this).find("td:eq(1)").text();
if (col_val == "CONFIRMED"){
$(this).addClass('selected'); //the selected class colors the row green//
} else {
$(this).addClass('bad');
}
});
});
The CSS looks like this:
.selected {
background-color: green;
color: #FFF;
}
.bad {
background-color: red;
color: #FFF;
}
The html table is generated from a pandas dataframe in my Django view and passed in like this:
<div class="table-responsive" style="margin-left: 15%; margin-right: 15%; overflow:auto;">
{{ datatable | safe }}
</div>
The problem is that it's coloring all of my rows red. Can anyone tell me what I'm doing wrong?
Since you use ==="CONFIRMED" make sure it's really: UPPERCASE, and that there's no leading or ending spaces " CONFIRMED" or "CONFIRMED " in the HTML.
The code you're showing will color .selected the entire row whos :eq(1) TD has the "CONFIRMED" content:
$(function(){
$("tr").each(function(){
var col_val = $(this).find("td:eq(1)").text();
if (col_val == "CONFIRMED"){
$(this).addClass('selected'); //the selected class colors the row green//
} else {
$(this).addClass('bad');
}
});
});
.selected{
background-color:green;
}
.bad{
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td><td>CONFIRMED</td>
</tr>
<tr>
<td>2</td><td>UNCONFIRMED</td>
</tr>
</table>
nothing bad about it.
if that's not what you see on your screen note that :eq() is index based, and elements index start at 0 so :eq(0) is probably what you want?
Another probable thing is that you don't have the exact content string set as "CONFIRMED" but probably there's some spaces before or after - so make sure to trim them using $.trim()
if( $.trim(col_val) === "CONFIRMED" )
if you additionally want to make your code even more flexible about the UPPERCASE or Capitalization you can do as:
if( $.trim(col_val.toLowerCase() ) === "confirmed" )
// Will work on "CONFIRMED", "Confirmed", "conFIRMed" etc
<style>
tr[data-stat="confirmed"]{
background-color: green;
color: #fff;
}
tr[data-stat="unconfirmed"]{
background-color: red;
color: #fff;
}
</style>
<table>
<tr data-stat="confirmed">
<td>1</td>
<td>Confirmed</td>
<td>bla.. bla.. bla..</td>
</tr>
<tr data-stat="unconfirmed">
<td>2</td>
<td>Not Confirmed</td>
<td>bla.. bla.. bla..</td>
</tr>
</table>
To find the first column in a row, you want to use the first-child selector. You can iterate over every first column with the each function.
We then look at the text and then add the appropriate class to the column's parent (tr).
$(document).ready(function() {
$("td:first-child").each(function() {
if ($(this).text() === "Confirmed") {
$(this).parent().addClass("green");
}
else {
$(this).parent().addClass("red");
}
});
});
http://jsfiddle.net/cw43ejjf/
If you are looking for the first column in the row you want to use:
var col_val = $(this).find("td:eq(0)").text();
Change the td:eq(1) to td:eq(0)
I have a table where I need fixed td sizes and as such I have the appropriate table-layout: fixed, white-space: nowrap, overflow:hidden, etc etc on the table and td's. It was working great until I had to dynamically resize it by basically adding a row at runtime
Basically I use javascript to add a row
<tr>
<td style="max-width:50px; min-width:50px; width:50px"> </td>
<td style="max-width:50px; min-width:50px; width:50px"> </td>
<td style="max-width:50px; min-width:50px; width:50px"> </td>
</tr>
It didn't work because some of the table td's are overflowing now. Well it turns out the td's even after this row somehow inherit asmax-width: none. When I manually add max-width:50px to an offending overflow td in firebug, the layout gets fixed.
Why is it ignoring the rules I set on the first tr and how can I set all td's to obey?
edit:
here is the fix width code as requested (there are two tables in the tableDiv):
fixWidths : function(tableDiv)
{
var headerTable = tableDiv.find('.headertable');
var widths = [];
headerTable.find("th").each(function(){
widths.push($(this).width());
});
var tr = tableDiv.find('.fixwidth');
for (var i = 0; i < widths.length; ++i)
{
var td = $(document.createElement('th'));
td.css('width', widths[i]);
td.css('min-width', widths[i]);
td.css('max-width', widths[i]);
td.html(' ');
tr.append(td);
}
/* */
}
<table>
<thead>
<tr>
<td>sf</td>
</tr>
<tr>
<td>sf</td>
</tr>
<tr>
<td>sf</td>
</tr>
<tr>
<td>sf</td>
</tr>
</thead>
</table>
.red {
background-color: red;
}
.green {
background-color: green;
}
How can i make automatically add class red and green for TR with jQuery?
LIVE EXAMPLE: http://jsfiddle.net/2Htwx/
$('tr:odd').addClass('red');
$('tr:even').addClass('green');
Assuming you want every other row red or green, as per your JS-fiddle. Note that this is within each table, so you won't see red/green/red across ALL table rows.
If you want that, try this:
var oddFilter = function(index) {
console.log(index);
return (index % 2) == 1;
},
evenFilter = function(index) {
console.log(index);
return (index % 2) == 0;
}
$('tr').filter(oddFilter).addClass('red').end()
.filter(evenFilter).addClass('green');
Note that <thead>, <tfoot> etc can still mess up the display, since that moves rows around the display.
You don't need JavaScript to accomplish this 'table-striping' effect. Use of the CSS nth-child selector will do the trick
thead tr {
background: green; /* Set all tr elements to green */
}
thead tr:nth-child(even) {
background: red; /* Override the colour for just the even ones */
}
Note: This selector is not supported in older browsers. IE8 and down.
Further reading on CSS nth-child:
http://css-tricks.com/how-nth-child-works/
You mean like this?
$(document).ready(function() {
var class = "";
$("tr").each(function(idx, elem) {
class = (idx % 2 == 0)?"red":"green";
$(elem).addClass(class);
});
});
Could you please explain "automatically"?
You mean at page ready event?
Maybe somthing like this:
$(document).ready(function (){
$("tr:odd").css("background-color", "#f00");
$("tr:even").css("background-color", "#0f0");
});
Here's the simplest method:
$("tr").addClass("red");
try this
var trs = jQuery('tr');
trs.filter(':even').addClass('red');
trs.filter(':odd').addClass('green');
to not selecting two-times every tr
I have to change colors for alternative rows. one row in "Green" and another one is in "Yellow".
<tr class="ms-viewheader" vAlign="top">
<tr class="">
<tr class="ms-alternating">
<tr class="">
<tr class="ms-alternating">
<tr class="">
<tr class="ms-alternating">
<tr class="">
<tr class="ms-alternating">
I have to skip "ms-viewheader" row and start coloring next sibling. Full row should be in
color.
How to do this?
run something like this in javascript
// define the background color for even and odd rows
var bgColors = {
even: '#eaeaea',
odd: '#aeaeae'
};
$("table tr:not(.ms-viewheader):even").css({"backgroundColor":bgColors.even});
$("table tr:not(.ms-viewheader):odd").css({"backgroundColor":bgColors.odd});
Ok, so you want to just handle this one table. Try this:
$("table[class='ms-listviewtable'] tr[class='']").css("background-color","yellow");
$("table[class='ms-listviewtable'] tr:.ms-alternating").css("background-color","green")
I am assuming that the table has a class, otherwise you could add a class to it to differentiate it.
Demo:
http://jsfiddle.net/J7dVX/13/
Does it have to use JS? Here's a CSS solution.
http://jsfiddle.net/HvLRs/1/
CSS:
tr:nth-child(2n) {
background-color:green;
}
tr:nth-child(4n) {
background-color:yellow;
}
HTML:
<table id="alternating">
<th class="ms-viewheader" vAlign="top"><td>Header</td></th>
<tr class=""><td>1</td></tr>
<tr class="ms-alternating"><td>2</td></tr>
<tr class=""><td>3</td></tr>
<tr class="ms-alternating"><td>4</td></tr>
<tr class=""><td>5</td></tr>
<tr class="ms-alternating"><td>6</td></tr>
<tr class=""><td>7</td></tr>
<tr class="ms-alternating"><td>8</td></tr>
</table>
If you must use jQuery, I modified Teddy's code: http://jsfiddle.net/HvLRs/3/
$("table tr:.ms-alternating:even").css("background-color","yellow");
$("table tr:.ms-alternating:odd").css("background-color","green");
If you want to treat ms-viewheader the same as ms-alternating:
$('tr:not([class^="ms"])').css('background-color','red');
$('tr[class^="ms"]').css('background-color','blue');
otherwise, if you just want to skip ms-viewheader and start alternating all the other rows:
$('tr:not([class^="ms"])').css('background-color','red');
$('tr.ms-alternating').css('background-color','blue');
Proof of concept: http://jsfiddle.net/daybreaker/J7dVX/
If you need to do it dynamically, use:
$("tr[class='']").css("background-color", "green");
$(".ms-alternating").css("background-color", "yellow");
As an alternative you could also use:
$(".ms-viewheader").siblings().css("background-color", "green");
$(".ms-alternating").css("background-color", "yellow");
Something like this - use modulus
for row, i in $('tbody tr')
color = if i % 2 is 0 then '#ff0000' else '#00ff00'
$(row).css 'background-color', color
I see in your latest comment on the original question that the ms-alternating class is already there in the markup for you??
If so, you shouldn't need any jquery or fancy CSS3 rules to do this. You can do this with regular ol' CSS.
Just add this to your CSS:
tr td {
background-color:green; /* this colors the whole table green */
}
tr.ms-viewheader td {
background-color:transparent; /* we don't want the header to get any color, so reset it */
}
tr.ms-alternating td {
background-color:yellow; /* and finally, color the alternating rows yellow */
}
Please note, this will color all tables on the page. You probably only want to target a single table. So you need some more specific selectors. Does the table you want to color have an ID or class on it you could target?
Good luck!
I am pulling back a large amount of tabular data that I wish to display using a table. The only caveat is that I would like to be able to "lock" a few of the columns (fname/lname/email) so that when users scroll horizontally those columns always stay "locked" in place and are visible. I have done something similar to this before but that was back in the frameset days so that approach is no longer valid.
I was thinking about doing something clever with laying tables on top of each other but so far I have had no success with making this work. Anyone have any clever suggestions?
A perfect example of what I am trying to do is here:
http://www.google.com/squared/search?q=world+leaders
If I understood correctly what you want, you can have a container div with position: relative, overflow: auto and fixed width. Inside of it, you separate the part you want to be locked, from the other one, into say, two different divs. The div containing the "locked" part should have position: absolute and left: 0.
It's just the big picture but you should be able to accomplish what you want this way.
The code below should be pretty self-explanatory. You can add/remove rows from TBODY while THEAD remains perfectly static. This is what TBODY and THEAD exist for ;)
<style type="text/css" media="screen">
.myTable
{
border:1px solid #000;
border-spacing:0px;
width:300px
}
.myTable thead td
{
background-color:#000;
color:#FFF;
}
.myTable tbody
{
height:300px;
overflow-y:auto;
overflow-x:hidden;
}
</style>
<table class="myTable">
<thead>
<tr>
<td>Fname</td>
<td>Lname</td>
</tr>
</thead>
<tbody>
<tr>
<td>Lior</td>
<td>Cohen</td>
</tr>
<tr>
<td>Lior</td>
<td>Cohen</td>
</tr>
<!-- put more rows here -->
</tbody>
</table>
Something like this should work:
You are going to have to play with it a little so that you don't have the horizontal scroll bar as well, but you get the idea.
Of course, this didn't work in IE7. It may work in 8, but as always YMMV. Good luck. I hope this gets you started in the right direction.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var body = $('#table-body');
for (var i = 0; i < 100; i++) {
var row = $('<tr />');
var fname = $('<td />')
.text('FirstName' + i);
var lname = $('<td />')
.text('LastName' + i);
var email = $('<td />')
.text('FirstLast' + i + '#example.com');
row
.append(fname)
.append(lname)
.append(email);
body.append(row)
}
});
</script>
<style type="text/css">
#table-body {
height: 150px;
overflow: auto;
}
</style>
</head>
<body>
<table>
<thead>
<td>First Name</td>
<td>Last Name</td>
<td>Email</td>
<thead>
<tbody id="table-body">
</tbody>
</table>
</body>
</html>