You need to be careful where and when you do your JS computation
<!DOCTYPE html>
<html>
<head>
<script>
var myList = document.getElementsByTagName('h1');
console.log(myList.length)
</script>
</head>
<body>
<div class='item'>
<h1 id="Python">Python</h1>
</div>
<div class='item'>
<h1 id="C++">C++</h1>
</div>
<div class='item'>
<h1 id="PHP">PHP</h1>
</div>
</style>
</body>
</html>
Will give you 0, because the Javascript is called before any parsing of the HTML body by your browser.
You need either :
- to wait the page load
<!DOCTYPE html>
<html>
<head>
<script>
window.onload = function(){
var myList = document.getElementsByTagName('h1');
console.log(myList.length)
}
</script>
</head>
<body>
<div class='item'>
<h1 id="Python">Python</h1>
</div>
<div class='item'>
<h1 id="C++">C++</h1>
</div>
<div class='item'>
<h1 id="PHP">PHP</h1>
</div>
</style>
</body>
</html>
or write this javascript at the end of the page :
<!DOCTYPE html>
<html>
<head>
<script>
var myList = document.getElementsByTagName('h1');
console.log(myList.length)
</script>
</head>
<body>
<div class='item'>
<h1 id="Python">Python</h1>
</div>
<div class='item'>
<h1 id="C++">C++</h1>
</div>
<div class='item'>
<h1 id="PHP">PHP</h1>
</div>
</style>
</body>
</html>
Even better is to write it at the end of the page with the window.onload
. It will be shorter to reach the HTML part of your page and rendering would be faster (this is significant for large amount of JS, but in this case, you should do file inclusion)