javascript - 关于使用 JavaScript 和 DOM 接口遍历 HTML 表格的问题
问题描述
但我有两件事我无法弄清楚。
首先是如何为所有 td 元素添加类名?
第二,我如何将此表注入名为“main”的 div,而不是 document.getElementsByTagName("body")[0];
document.getElementsByTagName("body") 末尾的[0]我不是很懂,为什么需要呢?
解决方案
第一个是如何为所有的td元素添加一个类名?第一个是如何为所有的td元素添加一个类名?
类列表.add
第二,我如何将这个表注入一个名为“main”的 div
getElementById
我不太明白 document.getElementsByTagName("body") 末尾的 [0]
因为 getElementsByTagName 是通用的。它可以返回任何标签的倍数。[0] 说“给我第一个”,因为它是 BODY,我们几乎可以肯定只有一个。
function start() {
// get the reference for the body
var mybody = document.getElementById("main");
// creates <table> and <tbody> elements
mytable = document.createElement("table");
mytablebody = document.createElement("tbody");
// creating all cells
for(var j = 0; j < 3; j++) {
// creates a <tr> element
mycurrent_row = document.createElement("tr");
for(var i = 0; i < 4; i++) {
// creates a <td> element
mycurrent_cell = document.createElement("td");
mycurrent_cell.classList.add("myClass");
// creates a Text Node
currenttext = document.createTextNode("cell is row " + j + ", column " + i);
// appends the Text Node we created into the cell <td>
mycurrent_cell.appendChild(currenttext);
// appends the cell <td> into the row <tr>
mycurrent_row.appendChild(mycurrent_cell);
}
// appends the row <tr> into <tbody>
mytablebody.appendChild(mycurrent_row);
}
// appends <tbody> into <table>
mytable.appendChild(mytablebody);
// appends <table> into <body>
mybody.appendChild(mytable);
// sets the border attribute of mytable to 2;
mytable.setAttribute("border","2");
}
start();
.myClass {
color:red;
}
<div id="main"></div>
推荐阅读
- python - 解决方案在 Python Gurobi 的线性规划中不可行
- python-3.x - 使用 BeautifulSoup 抓取多个网页
- python - 错误:使用序列设置数组元素。Keras 神经网络
- c++ - QImage:如何将灰度图像转换为 RGB 热图
- vb.net - 显示结束函数警告的匿名函数
- mysql - 防止不和谐机器人崩溃(mysql)
- jenkins - Ansible - Jeniks 管道太慢,无法将文件复制到网络位置
- javascript - Ajax 调用未到达 Laravel 控制器
- java - 如何使用@Rule 在 JUnit 中获得测试时间?
- vb6 - VB6 中的数据网格