Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

230
Visualizações
JavaScript simple function(e)

Can someone explain me why the function doesn't work when there are no arguments in the parentheses? I mean exactly "button" and "e". It seems to me that since a function is written for every "btns" element, it should automatically refer to it.

const btns = document.querySelectorAll('.question-btn');

btns.forEach(function(button){
    button.addEventListener('click', function(e){
        const question = e.currentTarget.parentElement.parentElement;
        question.classList.toggle('show-text');
    })
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you mean you don't understand why you need button and e in the parameter lists and can't just have:

const btns = document.querySelectorAll('.question-btn');

btns.forEach(function(/*no `button` here*/){
    ???.addEventListener('click', function(/*no `e` here*/){
        const question = ???.currentTarget.parentElement.parentElement;
        question.classList.toggle('show-text');
    })
});

...then answer is the ??? in the above. The button parameter¹ is how the forEach callback code can refer to the specific button being handled by that call to the forEach callback (the button that forEach passed as an argument¹ to the callback when calling it); without it, it doesn't have anything to work with. Similarly, the e parameter is how the event handler code can refer to the event it's handling (the event argument that the event system in the browser called the function with).

Here's what may be a simpler example of the button thing:

function setUpHandler(button) {
    button.addEventListener("click", function() {
        console.log("Clicked!");
    });
}

const btn1 = document.getElementById("btn1");
setUpHandler(btn1);
const btn2 = document.getElementById("btn2");
setUpHandler(btn2);
<input type="button" class="question-btn" id="btn1" value="Button 1">
<input type="button" class="question-btn" id="btn2" value="Button 2">

The two calls to setUpButton there are just like the two calls that forEach would make to it if we did this (except that forEach would also pass further arguments [the index and the list] that setUpHandler just ignores because it doesn't declare parameters to receive them in):

document.querySelectorAll(".question-btn").forEach(setUpHandler);

The button in setUpHandler is the parameter that the function receives that first argument in.


¹ Just a quick note on the terms "parameter" and "argument" since they came up above:

function add(a, b) {
//           ^−−^−−−−−−−−−−−−−−− "parameters"
    return a + b;
}
const sum = add(1, 2)
//              ^−−^−−−−−−−−−−−− "arguments"
console.log(sum);

A parameter is the named thing (like a variable) that a function uses to refers to the argument passed to it when it's called. In the above, the parameters are a and b. The arguments are the values 1 and 2. (And we also pass console.log an argument: sum.)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda