我想得到身体标签的长度或项目.但是,似乎getElementsByTagName在NodeList方面不起作用.我怎样才能做到这一点?
<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>
Run Code Online (Sandbox Code Playgroud)
谢谢.
[编辑]我添加了整个身体.
<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>
Run Code Online (Sandbox Code Playgroud)
关闭body元素后放置脚本代码.如果在创建元素之前尝试访问该元素,则无法找到该元素.例如,以下内容应该为您提供您期望的结果:
<html>
<head>
</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>
<!-- script code moved -->
<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>
</html>
Run Code Online (Sandbox Code Playgroud)