I'm starting javascript and I have a problem. I want to create a FAQs website and when you click on a question, the answers are displayed. But when I click on the question I see this error in the browser log Can not read property 'getAttribute' of null and it does nothing I have seen that the class exists, that it has captured the element, and it does not I can look more. Attached html code and current javascript. Thanks in advance. By the way I want to do it by delegation of events
(function(){
window.addEventListener('load', function(){
var elementosH2 = faqs.getElementsByTagName("h2");
var nodoH2;
for(var i=0; i<elementosH2.length;i++){
nodoH2 = elementosH2[i];
nodoH2.addEventListener("click", cambiar);
}
function cambiar(e) {
var h2 = e.target; // h2 es el nodoH2 actual
if (h2.getAttribute("class") == "mas") {
h2.setAttribute("class", "menos");
}
else {
h2.setAttribute("class", "mas");
}
if (h2.nextElementSibling.getAttribute("class") == "cerrado") {
h2.nextElementSibling.setAttribute("class", "abierto");
}
else {
h2.nextElementSibling.setAttribute("class", "cerrado");
}
}
});
}());
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title> Ejercicio FAQs</title>
<script src="script.js" defer></script>
</head>
<body>
<section id="faqs">
<h1>FAQs</h1>
<h2 class="mas"><img src="mas.jpg"/> ¿Qué es jQuery?</h2>
<div class="cerrado">
<p>
<img name="" src="menos.jpg"/>
jQuery es una librería de funciones JavaScript que puedes utilizar para desarrollar sitios web.
</p>
</div>
<h2 class="mas"><img src="mas.jpg"/>¿Por qué es tan popular jQuery?</h2>
<div class="cerrado">
<p>
<img src="menos.jpg"/>Hay tres razones:
</p>
<ul>
<li>Es gratuito</li>
<li>Te permite hacer más cosas en menos tiempo</li>
<li>Sus funciones son compatibles con todos los navegadores</li>
</ul>
</div>
</section>
</body>
</html>