我想获取 body 标签的长度或项目。 但是,就 NodeList 而言,getElementsByTagName 似乎不起作用。 我该怎么做?
<script type=text/javascript>
var b = document.getElementsByTagName('body');
console.log(b); // <body>...</body>
console.log(b.length); // 0
console.log(b[0]); // undefined
console.log(b.item(0)); // null
</script>
谢谢。
[编辑] 我添加了整个 body 。
<html>
<head>
<script type=text/javascript>
var b = document.getElementsByTagName('body');
console.log(b); // <body>...</body>
console.log(b.length); // 0
console.log(b[0]); // undefined
console.log(b.item(0)); // null
</script>
</head>
<body>
<div id='test'>
<h2>Hello</h2>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
<p>test</p>
</body>
</html>
最佳答案
将脚本放在页面的末尾,或者将它放在一个函数中,并在整个页面加载完成后调用它。
关于javascript - document.getElementsByTagName 不起作用。如何获取主体的 NodeList 的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9644456/