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

164
Visualizações
Display different content on each click using JS

I've got an example code of what I'm trying to do - where when you click on one of the size's i.e the li then it would display the size & price of that item in a new div called price.

What currently happens is no matter which li i choose the first size & price is displayed and it keeps added a new div. Where what i want is for whatever li that is clicked to be displayed and for the inner content of the div to be replaced each time. Any help on where i'm going wrong would be appreciated.

var sizeSelector = document.querySelectorAll('.container li');
sizeSelector.forEach(function(el) {
  el.addEventListener('click', function() {
    runFunction();
  });
});

function runFunction() {
  var newPrice = document.querySelector('.container li').innerHTML;
  document.querySelector('.container').insertAdjacentHTML("afterend", "<div class='price'>" + newPrice + "</div>");
  console.log(newPrice);
}
<ul class='container'>
  <li>Size Small $20</li>
  <li>Size Medium $30</li>
  <li> Size large $40</li>
</ul>

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

0

The code you used just needed a little adjustment to the runFunction and for the div containing the price class to be included in the original HTML template. By doing that, we can target that div and update its content by itself.

 var sizeSelector = document.querySelectorAll('.container li'); sizeSelector.forEach(function(el) { el.addEventListener('click', function(evt) { runFunction(evt); }); }); function runFunction(evt) { const newPrice = document.querySelector('.container li').innerHTML; const priceDiv = document.querySelector('.price'); priceDiv.innerHTML = evt.target.innerHTML; console.log(priceDiv.innerHTML); }
 <ul class='container'> <li>Size Small $20</li> <li>Size Medium $30</li> <li>Size large $40</li> </ul> <div class='price'></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