Home > OS >  Display multiple "innerText" on the same <li> element
Display multiple "innerText" on the same <li> element

Time:04-23

I have the following code:

<div id=payments></div>

<script>

  var payment01 = 100*0.2
  var payment02 = 100*0.05
  var payment03 = 100*0.7

  var list = document.createElement("li");
     list.innerText = `${payment01}`;                
     document.getElementById("payments").appendChild(list);

</script>

So my result is something like:

  • 20

What i'm trying to do, is to display all the payments on the same list, like this:

  • 20
  • 5
  • 70

What do i need to do to my list.innerText to display the other results, as well as any other results i might need to display in the future?

CodePudding user response:

You could make each of them an li element child of a ul

<div id=payments></div>

<script>

  var payment01 = 100*0.2
  var payment02 = 100*0.05
  var payment03 = 100*0.7

  var list = document.createElement("ul");
  var item1 = document.createElement("li");
  var item2 = document.createElement("li");
  var item3 = document.createElement("li");

  item1.innerText = `${payment01}`;
  item2.innerText = `${payment02}`;
  item3.innerText = `${payment03}`;

  list.appendChild(item1);
  list.appendChild(item2);
  list.appendChild(item3);
  document.getElementById("payments").appendChild(list);

</script>

CodePudding user response:

If you only have 3 payment vars, you can go this way. Otherwise you should use a loop to iterate over all your payments.

<script>

  var payment01 = 100*0.2
  var payment02 = 100*0.05
  var payment03 = 100*0.7

  var list = document.createElement("ul");
     list.innerHTML = `<li>${payment01}<\/li><li>${payment02}<\/li><li>${payment03}<\/li>`;
     document.getElementById("payments").appendChild(list);

</script>```

CodePudding user response:

You need to use a loop. Add them to an array and create a new list item element for each one. Highly suggest reading about them here if you are new.

<!DOCTYPE html>
<html>
  <body>
    <div id="payments"></div>

    <script>
      const payment01 = 100 * 0.2;
      const payment02 = 100 * 0.05;
      const payment03 = 100 * 0.7;

      const payments = [payment01, payment02, payment03];
      const paymentsDiv = document.getElementById("payments");

      for (const payment of payments) {
        const list = document.createElement("li");
        list.innerText = `${payment}`;
        paymentsDiv.appendChild(list);
      }
    </script>
  </body>
</html>
  • Related