javascript - getElementsByTagName ("table") - 以奇怪的方式获取 td

标签 javascript html html-table

我有这个简单的例子

 <table border="1px">
  <tr> 
    <td> </td>
    <td> <input type="button" value="Click" onclick="insertText()"/> </td>
  </tr>
 </table>

我想获取(第一个)tr 元素的第一个 td 元素,我试过:

var td = document.getElementsByTagName("table")[0].children[0].children[0];

因为它是:

  • var td = document.getElementsByTagName("table")[0] 表元素本身
  • children[0] 为 tr 元素
  • children[0] 再次用于第一个 td 元素

这就是我的想法,但显然这会返回 tr 元素并且只添加另一个 .children[0] 就得到了 td 元素。

var td = document.getElementsByTagName("table")[0].children[0].children[0].children[0];

这是为什么,或者我错过了什么?

最佳答案

那是因为你忘记了 <tbody>元素,自动插入到 DOM 中。

你的 table 到底是什么样子的:

<table border="1px">
  <tbody>
    <tr> 
      <td> </td>
      <td> <input type="button" value="Click" onclick="insertText()"/> </td>
    </tr>
  </tbody>
</table>

因此,为什么您需要向下挖掘三个级别的子级以定位 <td>你想要的元素。

旁注:如果您想了解更多关于 <tbody> 的原因元素自动注入(inject) <table>如果元素未声明,see this question and its answers .

关于javascript - getElementsByTagName ("table") - 以奇怪的方式获取 td,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17704985/

相关文章:

azure-devops - 为 Azure Wiki 中的表行着色

javascript - 卡住列 HTML JavaScript

javascript - 使用 AngularJS 在 html 页面中显示 JSON 答案

javascript - Gulp 为所有路径提供 : render index. html

javascript - 如何使 radio 看起来像禁用但不指定禁用 ="disabled",仅使用 css 和 js

html - 我试图将这些元素置于背景图像的中心

html - 两列表 : one as small as possible, 其余占

javascript - 如何获取单击元素的类值并使用此值在 jquery 中此类最后一次出现后放置一段 html 代码

javascript - JSON 到数组 - 如何解析这样的结构?

php - 如何使用dreamweaver在MySQL中插入值