javascript getElementByTagName() 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22661651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getElementByTagName() not working?
提问by Nikhil
In my page I've got 3 table elements, I want to access the 3rd element using its tagname.
So, I used
document.getElementByTagName("table")[2];
Later, I tried to obtain value of an element in that table by
table.children[0].children[1].children[2].innerHTML;
Then, I tried to modify the already existing
<p>
element withid="ID"
.But I'm not getting the value modified?
在我的页面中,我有 3 个表格元素,我想使用其标记名访问第三个元素。
所以,我用
document.getElementByTagName("table")[2];
后来,我尝试通过以下方式获取该表中元素的值
table.children[0].children[1].children[2].innerHTML;
然后,我尝试
<p>
使用id="ID"
.但我没有修改价值?
Whats wrong with my script?
我的脚本有什么问题?
<!DOCTYPE HTML>
<html>
<body>
ID : <p id="ID"></p>
<body>
<table>
</table>
<table>
</table>
<table>
<tbody>
<tr>
</tr>
<tr>
<td>Name</td>
<td>Class</td>
<td>25</td>
</tr>
<tr>
</tr>
</tbody>
</table>
<script>
var table = document.getElementByTagName("table")[2];
var id = table.children[0].children[1].children[2].innerHTML;
document.getElementById("ID").innerHTML = id;
</script>
</body>
</html>
回答by Quentin
As with most DOM methods that return a Node list, the name is plural- getElementsByTagName
.
与大多数返回 Node 列表的 DOM 方法一样,名称是复数- getElementsByTagName
。
回答by Gaurang Tandon
It is document.getElementsByTagName
- plural form!
是document.getElementsByTagName
-复数形式!
Because it has the possibility to return multiple elements in a NodeList - hence Elements
.
因为它有可能在 NodeList 中返回多个元素 - 因此是 Element s
。
回答by Karim AG
document.getElementsByTagName "PLURAL"
document.getElementsByTagName "PLURAL"
回答by kp singh
use
利用
document.getElementsByTagName("table")[2];
instead of document.getElementByTagName("table")[2];
document.getElementsByTagName("table")[2];
代替 document.getElementByTagName("table")[2];