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

208
Visualizações
How can I get the correct response for the below code of adding an event listener?

for(var i = 0 ; i < document.querySelectorAll(".btn").length; i++){
  var btn = document.querySelectorAll(".btn")[i];
  var btnName = btn.innerHTML;
  btn.addEventListener("click",function(){
   console.log(btnName);
  });
}
body{
  margin: 0;
}
*{
  box-sizing: border-box;
}
.btn{
  border-style: none;
  background-color: blue;
  padding: 10px 20px;
  margin: 0 20px;
  color: white;
}
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
<button class="btn">w</button>
  <button class="btn">a</button>
   <button class="btn">s</button>
    <button class="btn">d</button>
     <button class="btn">k</button>
    <script src="script.js"></script>
  </body>
</html>

In the above code, I want to print the inner HTML of the button in the console, when clicked, but instead of getting a specific result for specific buttons, I am getting the same value for every button which is the last button inner HTML.

for Example: problem: when I click the w button "k" gets printed in console instead of "w". when I click the a button "a" gets printed in console instead of "a". when I click the k button "k" gets printed.

desired result: when I click the w button "w" gets printed in console. when I click the a button "a" gets printed in console. when I click the k button "k" gets printed in console.

How can I print the specific inner HTML of a specific button?

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

0

You should cache the elements

const buttons = document.querySelectorAll(".btn");
for(let i = 0 ; i < buttons.length; i++){
   button[i].addEventListener("click",function(){
     console.log(this.textContent);
  });
}

or use forEach

function myClick(){
  console.log(this.textContent);
});
window.addEventListener("DOMContentLoaded", function() {
  document.querySelectorAll(".btn")
   .forEach(btn => btn.addEventListener("click",myClick));
})

But instead PLEASE delegate from the nearest static container

window.addEventListener("DOMContentLoaded", function() {
  document.getElementById("container").addEventListener("click", function(e) {
    const tgt = e.target.closest("button.btn");
    if (tgt) console.log(tgt.textContent);
  });
});

window.addEventListener("DOMContentLoaded", function() {
  document.getElementById("container").addEventListener("click", function(e) {
    const tgt = e.target.closest("button.btn");
    if (tgt) console.log(tgt.textContent);
  });
});
body {
  margin: 0;
}

* {
  box-sizing: border-box;
}

.btn {
  border-style: none;
  background-color: blue;
  padding: 10px 20px;
  margin: 0 20px;
  color: white;
}
<div id="container">
  <button class="btn">w</button>
  <button class="btn">a</button>
  <button class="btn">s</button>
  <button class="btn">d</button>
  <button class="btn">k</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