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

107
Visualizações
How to select span within a dynamically generated button?

Problem: How to update the innerHtml of a span within a dynamically generated button using only JavaScript?

I'm building a 'like' feature (think social media) where users can like/unlike posts, but I can't figure out how to select the value of the specific span the user clicks on. I've been only able to find jQuery solutions using .find('span')

const htmlBtn = `<button class="count"><span>0</span></button>`;

const create = document.getElementById("create");
create.addEventListener("click", (e) => {
  const container = document.createElement("div");
  container.className = "container";

  container.innerHTML = htmlBtn;
  document.getElementById("app").append(container);
});

const app = document.getElementById("app");
app.addEventListener("click", (e) => {
  const btn = e.target;
  /*
  each time someone click nth button, span within nth button increments by 1
  
  let count = document.querySelector("span").innerHTML;
  count++;
  document.querySelector("span").innerHTML = count;
  */
});
<button id="create">Create</button>

<div id="app"></div>

Expected outcome: User clicks the button to increment the span of only that button by 1.

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

0

e.target.children will give you an array of all the children of button and the 0th index of the array should be your span element which you can then edit normally using the innerHTML method.

In your case,

let count = parseInt(e.target.children[0].innerHTML);
e.target.children[0].innerHTML = count + 1;
about 4 years ago · Juan Pablo Isaza Relatório

0

create.addEventListener("click", (e) => {
  const container = document.createElement("div");
  container.className = "container";

  container.innerHTML = htmlBtn;
  document.getElementById("app").append(container);

  container.addEventListener("click", (e) => {
    const value = +e.target.innerHTML;
    e.target.innerHTML = (value + 1).toString();
  });
});
about 4 years ago · Juan Pablo Isaza Relatório

0

The methods querySelector() and querySelectorAll() can be called on a specific parent element, similar to find() in jQuery.

Make sure to use e.currentTarget and not e.target in the event listener, in order to refer to the element that handles the event and not to any child element.

Example - click any of numbers to increment.

function clickToIncrement(e) {
  const innerSpan = e.currentTarget.querySelector('span');
  
  if (innerSpan) {
    innerSpan.textContent++;
  }
}

document.getElementById('div1').addEventListener('click', clickToIncrement);
document.getElementById('div2').addEventListener('click', clickToIncrement);
<div id="div1">
  <span>0</span>
</div>
<div id="div2">
  <span>0</span>
</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