使用setAttribute将id设置为元素最后一行的td

set id using setAttribute to td of last row of element

本文关键字:一行 td 最后 setAttribute id 设置 元素 使用      更新时间:2023-09-26

我正在生成一个表行,它在html中动态地包含两列,其中包含数据库中的值。我希望第一列的每个td都有一个唯一的id,我已经做到了,但我不能将id设置为表中最后一行的td。这是设置id 的代码

<script>
var i=0;
var id=1;
while(i<100)
{
document.getElementsByTagName("td")[i].setAttribute("id", id);
i=i+2;
id=id+1;
}
</script>

如有任何帮助,将不胜感激

但是我无法将id设置为表中最后一行的td。

你需要先到表格的最后一行。

var allRows = document.getElementsByTagName("tr");
var lastRow = allRows[allRows.length - 1];

现在将Id设置为最后一行的第一个td

lastRow.getElementsByTagName("td")[0].setAttribute("id" , allRows.length + 1 );
提供DOM选择器是有原因的。:)
var tds = $('tr td:first-child');
var i=0;
$.each(tds, function(){
    $(this).attr('id',i++);
});

使用纯javascript

var tds = document.querySelectorAll('tr td:first-child');
var i = 0;
for(var td in tds){
    tds[td].setAttribute('id',i++);
    // or
    //tds[td].id=(i++).toString();
};

您可以使用querySelectorAll获取给定表中的所有第一个td,使用:first child;它将返回需要在数组中转换为的NodeList。

var arrTD = document.querySelectorAll("#list-notification tr td:first-child");
    arrTD = Array.prototype.slice.call(arrTD);
    var i =0;
    arrTD.forEach(function(val,key){ 
                  val.setAttribute('id',i);
                  ++i   
    })