I want to get an element tag printed in the console just by clicking on it

I want to get an element tag printed in the console just by clicking on it but it doesn’t seem to work and I don’t get why?

can anyone point the error in my logic?

let bodyChildren = document.body.children;
let bodyArr = Object.values(bodyChildren);

for (i = 0; i < bodyChildren.length; i++) {
    bodyArr[i].onclick = function () {
        console.log(bodyArr[i].tagName);
    };
}

Answer

The problem is that when you define a function, everything in it is contained in a separate scope. Within the function bodyArr is not known. You can use this instead to refer to the clicked element, like below:

document.body.children will only refer to the direct children of the body element. If you want to refer to every element in the DOM, you can use document.getElementsByTagName("*") instead.

When the code is written globally, like in the snippet below, the variable bodyArr is actually available in the global scope, as is the variable i. But keep in mind that the code inside the function is only executed when an element is clicked. At that point in time the for loop has been fully executed leaving i with the value 3 (since in the snippet below the script tag also counts). bodyArr will always contain exactly 1 element less, no matter how many elements are in the DOM. In this case it has 3 elements with the last element being saved at position 2 (zero based) in the array, hence bodyArr[i] equals undefined.

let bodyChildren = document.body.children;
let bodyArr = Object.values(bodyChildren);
for (i = 0; i < bodyChildren.length; i++) {
      bodyArr[i].onclick = function () {
        console.log(this.tagName);
      }
}
<span>child1</span>
<p>child2</p>