Problem with console
Lvhau_1529 (1)

I want to show it all inside HTMLCollection {}. What should I do?

You are viewing a single comment. View All
JustARatherRidi (213)

First off, why your HTMLCollection in your console is empty is because your <script> tag is at the top of your <body>, so the DOM has not yet loaded when your script is run. Two ways to solve this are:

  • Put the <script> tag at the bottom of your <body> tag, so that all the other tags load before your script.
  • Or put all your code inside a function, and assign it to window.onload. This makes it so that the code runs only after everything has loaded.
window.onload = function() {
    let x = document.getElementsByTagName('li');

    // The rest of your code goes here

Doing only the first one seems to work in this case, but just to be sure it doesn't break later on, it is usually a good practice to do the second one as well.

Secondly, to show all the tags, either you can use a for-of loop

const tags = document.getElementsByTagName('li');
for (let i of tags) {

Or you can convert the HTMLCollection to an array,

const tags = [...document.getElementsByTagName('li')];

And iterate over it however you want. You can also index the array. For example tags[1] will give you the second <li> element.

Hope this helped!