Javascript HTML 集合显示为 0 长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30211605/
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
Javascript HTML collection showing as 0 length
提问by Hyman hardcastle
var eval_table = document.getElementsByClassName("evaluation_table");
console.log(eval_table);
This displays as:
这显示为:
[item: function, namedItem: function]0:
table.widefat.fixed.evaluation_table
length: 1
__proto__: HTMLCollection
However, when I try to get a length of eval_table
, eval_table.length
, it returns a value of 0
. I've used this approach before, had no issues with this approach before. Is there anything wrong with what I'm trying to achieve above?
然而,当我试图得到的长度eval_table
,eval_table.length
,它返回的值0
。我以前使用过这种方法,以前对这种方法没有任何问题。我试图在上面实现的目标有什么问题吗?
回答by blankmaker
This is because your JS is running before the elements are rendered to the DOM. I bet the script you have running is loaded before the <body>
of your html. You have two options:
这是因为您的 JS 在元素呈现到 DOM 之前正在运行。我敢打赌你运行的脚本是在<body>
你的 html之前加载的。您有两个选择:
- Add the self-executing
<script>
as the last thing in your<body>
tag or; - Wrap your function so that it waits for the DOM to be loaded before executing. You can do this with either:
- jQuery's
$(document).ready
or - if you're not running jQuery:
document.addEventListener("DOMContentLoaded", function(e) {// do stuff })
- jQuery's
- 将自动执行添加
<script>
为<body>
标签中的最后一件事,或者; - 包装您的函数,以便它在执行之前等待 DOM 被加载。您可以通过以下任一方式执行此操作:
- jQuery
$(document).ready
或 - 如果您没有运行 jQuery:
document.addEventListener("DOMContentLoaded", function(e) {// do stuff })
- jQuery
Code sample below:
下面的代码示例:
<html>
<head></head>
<script>
document.addEventListener("DOMContentLoaded", function(e) {
var eval_table = document.getElementsByClassName('evaluation_table');
console.log(eval_table, eval_table.length);
});
</script>
<body>
<div class="evaluation_table"></div>
<div class="evaluation_table"></div>
<div class="evaluation_table"></div>
<div class="evaluation_table"></div>
</body>
</html>
回答by sachin.ph
You could write the code inside the
你可以在里面写代码
$('document').ready(function(){
// your code
});
or on body onload or on DOM ready
或在身体上加载或在 DOM 准备好
<body>
Your HTML here
<script>
// self executing function here
(function() {
var eval_table = document.getElementsByClassName("evaluation_table");
console.log(eval_table,eval_table.length);
})();
</script>
</body>
I have tried in this jsFiddle
我在这个jsFiddle 中尝试过
回答by giapnh
In order to access the element at position 0 of HTMLCollection you should use
为了访问 HTMLCollection 位置 0 的元素,您应该使用
setTimeout(() => {
let elms = document.getElementsByClassName('ClassName').item(0)
}, 0);
Using setTimeout
to make sure DOM is finished render.
使用setTimeout
以确保DOM完成渲染。