最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript DOM : add an attribute to a <tr> - Stack Overflow

programmeradmin3浏览0评论

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

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

Share edited Sep 6, 2010 at 7:15 Felix Kling 818k181 gold badges1.1k silver badges1.2k bronze badges asked Sep 6, 2010 at 7:08 Marouane GazanayiMarouane Gazanayi 5,2136 gold badges42 silver badges59 bronze badges 3
  • 2 Have you heard of jQuery? expect to about 10 times in the next twenty minutes. – jcolebrand Commented Sep 6, 2010 at 7:11
  • 1 don't make him include n use JQuery for this purpose. – sv_in Commented Sep 6, 2010 at 8:12
  • 1 @jcolebrand What a joy to read this ment 10 years after, now, you'll hear Angular/React/vue lol – Marouane Gazanayi Commented Dec 23, 2020 at 23:00
Add a ment  | 

5 Answers 5

Reset to default 6

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)

  1. 暂无评论