我想通过javascript选择一个特定的td想要放一些类

时间:2016-07-02 19:22:57

标签: javascript

我没有为此制作任何HTML,通过javascript创建表格。这是代码:

<code>
var container = document.createElement("div");
    var col_sm_12 = document.createElement("div");
    var tables = document.createElement("table");
    var tbody = document.createElement("tbody");
    tables.id = "first_table";
    for (var i = 0; i <= 10; i++){
        var tr = document.createElement("tr");
        for (var j = 0; j <= 5; j++){
            var column = document.createElement("td");
            var columntext = document.createTextNode("Hello " + j);
            column.appendChild(columntext);
            tr.appendChild(column);
            }
        tbody.appendChild(tr);
        }

    container.className = "container";
    col_sm_12.className = "col-sm-12";
    tables.className = "table table-bordered table-striped";
    container.appendChild(col_sm_12);
    col_sm_12.appendChild(tables);
    tables.appendChild(tbody);
    document.body.appendChild(container);   
</code>

请帮助我。 提前致谢

1 个答案:

答案 0 :(得分:0)

试试这个(对于td no.2或4):

for (var i = 0; i <= 10; i++){
    var tr = document.createElement("tr");
    for (var j = 0; j <= 5; j++){
        var column = document.createElement("td");
        var columntext = document.createTextNode("Hello " + j);
        if(j == 2 || j == 4){
            column.setAttribute('class','some-classes');
        }
        column.appendChild(columntext);
        tr.appendChild(column);
        }
    tbody.appendChild(tr);
}