I want to create a JavaScript function that parses my HTML page, get the Table by it's ID, and after that, add a class attribute to each <tr>
as if the line is the 1st, I'll add :
class="line1" to the <tr>
but if the line is the second, I'll add class="line2" to the <tr>
How to do please
views:
72answers:
5
A:
its very easy in jquery ... as below :-
$(document).ready(function() { //for table row $("tr:even").addClass("AlternateBG1"); $("tr:odd").addClass("AlternateBG2"); })
BUT IN JQUERY...
Amit
2010-09-06 07:20:50
A jQuery solution was not asked for.
J-P
2010-09-06 08:35:41
A:
With jQuery is really simple, do something like:
var i = 1;
$("#myTable tr").each(function() {
$(this).addClass("line"+i);
i++;
});
Where #myTable is your table id, and $(this) inside each function will be the current element on the cycle.
João Gala Louros
2010-09-06 07:21:07
I've voted your answer down because of the "just do it with jQuery" attitude that everybody seems to insists on having. Nothing personal obviously, but it's frankly kind of annoying by now, and it's so unnecessary in simpler scenarios such as this one.
Rob
2010-09-06 07:31:34
Plus, this doesn't even take advantage of the fact that each `tr`'s index is passed as the first argument to the `each` callback.
J-P
2010-09-06 08:32:41
That doesn't mean that is wrong. The function .each() for it self is already the slowest operation that you can do in JavaScript. If we go that way I should not use .each() function...
João Gala Louros
2010-09-06 19:15:36
+6
A:
If I understand you corrrectly, you want to alternate the class names to get some kind of zebra style right?
var table = document.getElementById('yourTableId');
var rows = table.rows;
for(var i = 0, l = rows.length;i < l; i++) {
rows[i].className = 'class' + ((i%2) + 1);
}
See the HTML DOM Table Object.
Felix Kling
2010-09-06 07:23:08
A:
It is easy without jQuery:
oTBody=document.getElementById("tBodyId");
//for (key in oTbody.childNodes) {
for (var nPos=0, nLength = oTbody.childNodes.length; nPos<nLegth; nPos++)}
oRow = oTbody.childNodes[nPos];
if (oRow && oRow.tagName && oRow.tagName.toLowerCase() == "tr") {
oRow.className = (bNormalRow? sClass1:sClass2);
bNormalRow = !bNormalRow;
}
}
pkario
2010-09-06 07:28:55
Don't use the `for(i in foo)` loop for array-like structures (e.g. NodeLists). It's slow (very) and can result in non-related items being looped over (if any prototypes in the prototype chain of `NodeList` have been manipulated).
J-P
2010-09-06 08:31:38
A:
var table = document.getElementById("yourTableId");
for(var i in table.rows){
table.rows[i].className = 'line'+(i+1).toString();
}
Anpher
2010-09-06 07:30:59
Don't use the `for(i in foo)` loop for array-like structures (e.g. NodeLists). It's slow (very) and can result in non-related items being looped over (if any prototypes in the prototype chain of `NodeList` have been manipulated).
J-P
2010-09-06 08:34:33