Ask coding questions

← Back to all posts
Problem with console
Lvhau_1529 (1)

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

JustARatherRidi (214)

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!

a5rocks (834)

Hmmm so I see two possible meanings to your question:

a) You want all your li tags to show up: Make your html have <li></li>

b) You want all your tags to show up: Use document.getElementsByTagName('*')

Lvhau_1529 (1)

I just want it to display like that