Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
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);
    };
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

You need to get ALL elements from the document body and this is KEY: var all = document.getElementsByTagName("*");

var all = document.getElementsByTagName("*");
let bodyArr = Object.values(all);

for (i = 0; i < bodyArr.length; i++) {
    bodyArr[i].onclick = function () {
        console.log(this.tagName);
    };
}
<span>Hello world</span>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!