1

I have a simple JS code like the following. When I click on the h2 element, I get a reference error saying that h2Elements is not defined on the console.log('h2Elements', h2Elements) when console.log('faqs', faqs) works fine.

Shouldn't h2Elements be defined like faqs is through closure?

<!DOCTYPE html>
<html lang="en">
<body>
    <main id="faqs">
        <h2><a href="#" >What is JavaScript?</a></h2>
        <div>
            <p>JavaScript is a programming language that's built into the major web browsers.
            </p>
        </div>
    </main>
    <script>
      var toggle = function() {
        console.log('faqs', faqs)
        console.log('h2Elements', h2Elements)
      };

      window.onload = function() {
          var faqs = document.getElementById("faqs");
          var h2Elements = faqs.getElementsByTagName("h2");

          for (var i = 0; i < h2Elements.length; i++ ) {
            h2Elements[i].onclick = toggle;
          }
      };
    </script>
</body>
</html>
dorachan2010
  • 981
  • 3
  • 12
  • 21
  • `toggle` method doesn't have the visibility to `h2Elements`. – gurvinder372 Feb 27 '18 at 06:22
  • where have you given id as `h2Elements` to any tag in html body? – DadyByte Feb 27 '18 at 06:22
  • `faqs` is not defined through closure, it's defined because [it has the same name as the id in HTML](https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables). – JJJ Feb 27 '18 at 06:22
  • I believe getElementsByTagName returns a collection not an element reference – McMurphy Feb 27 '18 at 06:30

1 Answers1

1

faqs and h2Elements are not in scope of toggle function. faqs variable inside toggle function is giving output because 'faqs' is id of some DOM element.

omi
  • 718
  • 3
  • 10