I want to get the length
of the returned class names
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:
console.log(removeButton)
I can see the list of items there.
I need the length so I can iterate through a for-loop
and assign the event listeners.
What seems to be the problem?
Solution
Check that the elements exist before trying to gather them with getElementsByClassName
You have to be sure the elements exist if your JavaScript code depends on them.
One way of achieving this by putting the <script>
tag at the end of the body like this:
<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
.
As OP stated,
Check that the elements exist before trying to gather them with getElementsByClassName.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.