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

161
Visualizações
Can't access button inside file 2 when inside template literals

I can't access this button when I try to access on some other file. It is working when I do it inside first file but not able to do on file 2? BTW, Css is working fine, if I create a CSS file and add some styling to the elements, it works, but not the javascript

file1.js
else {
  product_carousel_wrapper.innerHTML = recent.map(productData => 
`
  <h1>Hello</h1>
  <button class="click">CTest</button>
  <h1>Bye</h1>
`
).join('');
}
file2.js

document.querySelector('.click').addEventListener('click', () => {
  alert('Heyy');
});
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Attach a listener to the wrapper element and use event delegation to catch events from child elements that have been added to the DOM dynamically instead of attaching a listener to each button.

// FILE1

// Cache the wrapper
const wrapper = document.querySelector('.wrapper');

// Add the HTML
wrapper.innerHTML = `
  <button>CTest1</button>
  <button>CTest2</button>
  <button>CTest3</button>
`;

// FILE2

// Add a listener to the wrapper
wrapper.addEventListener('click', handleClick, false);

// Get the textContent (in this example)
// of the button that was clicked
function handleClick(e) {
  if (e.target.matches('button')) {
    console.log(e.target.textContent);
  }
}
<div class="wrapper"></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