Home > Software design >  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

Time:11-11

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);
    };
}

CodePudding user response:

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:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related