Search code examples
javascripthtmlinnerhtml

innerHTML basic, adding numbers in loop


I have trouble with javascript. I want to make it so that if I click on the adding candy button. It states There are 2 candy. If I click again it says There are 3 candy. What is the fastest way to do it using innerHTML?

function add() {
  var d = document.getElementById('idd').innerHTML;
  d = d + '<li>There is a candy</li>';
  document.getElementById('idd').innerHTML = d;
}
<body>
  <h1>Adding</h1>
  <p><input type="button" value="adding candy" onclick="add();"></p>
  <ul id="idd">
    <li>There is a candy.</li>
  </ul>
</body>

This is giving me a head ache all day long.


Solution

  • Generate new li element with content based on count of li and append it to the ul.

    function add() {
      // get the `ul` using id
      var d = document.getElementById('idd');
      // get count of `li` 
      var count = d.getElementsByTagName('li').length + 1;
      // create an li element
      var li = document.createElement('li');
      // add content to li based on count
      li.innerHTML = 'There is ' + (count) + ' candy.';
      // append generated li element to the ul
      d.appendChild(li)
    }
    <body>
      <h1>Adding</h1>
      <p>
        <input type="button" value="adding candy" onclick="add();">
      </p>
      <ul id="idd">
        <li>There is a candy.</li>
      </ul>
    </body>


    UPDATE : If you are trying to update the same li content then do it using a global variable.

    var count = 1;
    
    function add() {
      // get the li
      var d = document.querySelector('#idd li');
      // update content by based on count variable value
      d.innerHTML = 'There is ' + (++count) + ' candy.';
    }
    <body>
      <h1>Adding</h1>
      <p>
        <input type="button" value="adding candy" onclick="add();">
      </p>
      <ul id="idd">
        <li>There is a candy.</li>
      </ul>
    </body>