Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda