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>