Several reasons your query could fail:
- You are running the code too early, before that part of the DOM has been parsed.
- The DOM elements are created dynamically (by some other code) so you have to run your code after that code runs.
- There are errors in your HTML so what you think is in the page is not what the browser ends up parsing.
- There are errors in your javascript code so it aborts executing before doing everything you wanted it to.
The most common issue is #1. The fix is to either make sure your code is placed AFTER those elements in the page HTML, use a framework that tells you when the document is ready or subscribe to an event yourself so you can know when the document is ready.
If you're interested in a single plain javascript function call that can tell you when the document is ready in all browsers, you can grab the code here: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it though probably all you need to do is to move your <script>
tag after the DOM elements you want to query for (e.g. to the end of your HTML right before the </body>
tag like this:
<html>
<body>
<a href="#"><img class="img" src="image/100.jpg" alt="z"/></a>
<a href="#"><img class="img" src="image/200.jpg" alt="z"/></a>
<a href="#"><img class="img" src="image/400.jpg" alt="z"/></a>
<a href="#"><img class="img" src="image/300.jpg" alt="z"/></a>
<script>
var myitems = document.getElementsByClassName("img");
for (var z = 0; z <= myitems.length; z++) {
alert("hello" + myitems.length);
}
</script>
</body>
</html>