开发者

JavaScript DOM : add an attribute to a <tr>

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


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.


its very easy in jquery ... as below :-

$(document).ready(function() {
    //for table row
    $("tr:even").addClass("AlternateBG1");
    $("tr:odd").addClass("AlternateBG2");
})

BUT IN JQUERY...


var table = document.getElementById("yourTableId");
for(var i in table.rows){
  table.rows[i].className = 'line'+(i+1).toString();
}


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;
    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜