Home > Net >  Display different content on each click using JS
Display different content on each click using JS

Time:12-01

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

The code you used just needed a small 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 alone.

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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

function runFunction(el) {
  var newPrice = el.innerHTML;
  var priceDiv = document.querySelector('.price')
  priceDiv.innerHTML = newPrice
}
<ul class='container'>
  <li>Size Small $20</li>
  <li>Size Medium $30</li>
  <li> Size large $40</li>
</ul>

<div class="price">
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related