Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!