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

559
Visualizações
How do I make multiple buttons within the same class call to the same parameter function inside JavaScript?

I have a div with 3 different buttons labeled 1 - 3. Currently, all 3 buttons use an inline event that passes its innerHTML as a parameter:

<div class="theClass">
    <button onclick="doThing(this.innerHTML)">1</button>
    <button onclick="doThing(this.innerHTML)">2</button>
    <button onclick="doThing(this.innerHTML)">3</button>
</div>
<script>
    function doThing(num){
        ...
    }
</script>

In an effort to both avoid redundancy and avoid inline scripting, I want to know how it would be possible to do this without an inline for each button. How would I make multiple buttons within the same class call the same external script? That is to say, how can I format a function to recognize that a button inside a designated class has been clicked, get the innerHTML of that button, and then pass it as a parameter?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can select all buttons with querySelectorAll, loop through the NodeList and use addEventListener to add a click event listener that calls doThing and passes the element's innerHTML as a parameter to each button:

const buttons = document.querySelectorAll('button');

buttons.forEach(e => e.addEventListener('click', function(){ doThing(this.innerHTML) }))


function doThing(html){
  console.log(html)
}
<div class="theClass">
    <button>1</button>
    <button>2</button>
    <button>3</button>
</div>

Alternatively, you can use event delegation by adding a click event listener to the document and checking whether the target is a button (with Element.matches()), and if so, call doThing:

document.addEventListener('click', function(e){
  if(e.target.matches('button')){
    doThing(e.target.innerHTML)
  }
})
function doThing(html){
  console.log(html)
}
<div class="theClass">
    <button>1</button>
    <button>2</button>
    <button>3</button>
</div>

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