简体   繁体   English

getElementsByClassName不返回长度

[英]getElementsByClassName not returning length

I want to get the length of the returned class names 我想得到返回的类名的length

There are a series of buttons that I want to add event listeners to and they all share the same class name. 有一系列按钮我想要添加事件监听器,它们都共享相同的类名。

removeButton = document.getElementsByClassName("removeButton");

When I do removeButton.length I always get 0 but if I do: 当我执行removeButton.length我总是得到0但如果我这样做:

console.log(removeButton) I can see the list of items there. console.log(removeButton)我可以看到那里的项目列表。

I need the length so I can iterate through a for-loop and assign the event listeners. 我需要长度,所以我可以迭代for-loop并分配事件监听器。

What seems to be the problem? 什么似乎是问题?

Solution
Check that the elements exist before trying to gather them with getElementsByClassName 在尝试使用getElementsByClassName收集元素之前,请检查元素是否存在

You have to be sure the elements exist if your JavaScript code depends on them. 如果JavaScript代码依赖于它们,则必须确保元素存在。

One way of achieving this by putting the <script> tag at the end of the body like this: 实现此目的的一种方法是将<script>标记放在正文的末尾,如下所示:

<html>
<head></head>
<body>
<script type="text/javascript">
    // code here
</script>
</body>

You can also put all your code in a function for the window.onload event or use a library that provides this functionality, such as jQuery . 您还可以将所有代码放在window.onload事件的函数中,或者使用提供此功能的库,例如jQuery

As OP stated, 正如OP所说,

Check that the elements exist before trying to gather them with getElementsByClassName. 在尝试使用getElementsByClassName收集元素之前,请检查元素是否存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM