I was getting a problem .
When you call:
alert(document.getElementsByTagName("li").length);
You want to get an element that does not exist yet. because the head is the first thing that runs when you load the page.
it's searching for the li
element, but it isn't yet there when the head loads.
You have to put it in the body because then, the list items exist. then it works.
Generally scripts and CSS files must be fit into head, as good practice.
For more details about when to put in head and body tag, refer this link - Where should I put the CSS and Javascript code in an HTML webpage? & Should I write script in the body or the head of the html?
If you put script in head, javascript code gets executed even before controls in body tags are rendered. So if you want to keep your scripts in head tag, make sure they are executed once onload is completed. Below is an example:
<script type="text/javascript">
function MyFunction() {
alert(document.getElementsByTagName("li").length);
}
window.onload = MyFunction;
</script>