为何使用JavaScript无法获取table的tbody元素?
问题原因与解决办法
你遇到的核心问题是DOM API的属性命名规则差异:
<table>元素的<thead>和<tfoot>在规范中是唯一存在的,因此对应的DOM属性是单数形式:table.tHead、table.tFoot- 而
<tbody>允许在一个表格中存在多个,所以对应的DOM属性是复数形式:table.tBodies(注意是tBodies,不是你误用的tBody),它返回包含所有tbody元素的HTMLCollection。你使用了错误的属性名tBody,因此得到undefined。
解决方式
1. 使用标准复数属性获取
如果你的表格只有一个tbody,直接通过索引获取第一个元素即可:
let tbody = table1.tBodies[0];
2. 保留ID定位方式
你的tbody已经设置了明确的IDTB,通过getElementById获取是完全可靠的方案:
let tbody = document.getElementById('TB');
3. 使用选择器定位
也可以通过querySelector直接在table范围内筛选:
let tbody = table1.querySelector('tbody');
修正后的示例代码
以下是修正了tbody获取逻辑的JavaScript代码:
let table1 = document.getElementById("TBL1"); if (typeof(table1) != "undefined") { console.log(" - table element 'TBL1' acquired"); let thead = table1.tHead; if (typeof(thead) != "undefined") { console.log(" - table element table1.tHead acquired,"); thead.style.color = "#ffff50"; console.log(" thead color changed to " + thead.style.color); } else console.log(" OOPS - could not access table table1.tHead"); // 修正:使用tBodies[0]获取第一个tbody let tbody = table1.tBodies[0]; if (typeof(tbody) != "undefined") { console.log(" - table element table1.tBodies[0] acquired,"); tbody.style.color = "#504020"; console.log(" tbody color changed to " + tbody.style.color); } else console.log(" OOPS - could not access table table1.tBodies[0]"); let tfoot = table1.tFoot; if (typeof(tfoot) != "undefined") { console.log(" - table element table1.tFoot acquired,"); tfoot.style.color = "#ffff50"; console.log(" tfoot color changed to " + tfoot.style.color); } else console.log(" OOPS - could not access table table1.tFoot"); } else console.log("OOP - Couldn't acquire TBL1 table"); if (typeof(tbody) == "undefined") { tbody = document.getElementById("TB"); if (typeof(tbody) != "undefined") console.log(" - table element table1.tBody acquired using getElementById('TB'),"); tbody.style.color = "#504020"; console.log(" tbody color changed to " + tbody.style.color); } console.log(" - Done with table element access test");
内容的提问来源于stack exchange,提问作者CJH
相关产品推荐
相关产品推荐

