unable to delete random array elements on onclick event

I have an array and displaying its content wrapped up in a P tag on the body, now how do I delete the element when I click on the specific element.

JS:

var arr = [10, 20, 30];

var demo = document.getElementById('demo');
for( var i = 0; i < arr.length; i++) {
 demo.innerHTML += `<p class="tag">${arr[i]} </p>`;
 }

 var pTag = document.getElementsByClassName("tag");
 for( var j = 0; j < pTag.length; j++) {
  pTag[j].onclick = function() {
    arr.splice(pTag[j], 1);

   }
}

3 answers

  • answered 2018-04-17 05:41 CertainPerformance

    Use array methods instead - don't use var with asynchronous code, since it gets hoisted and has function scope instead of block scope.

    const arr = [10, 20, 30, 40, 50];
    const demo = document.getElementById('demo');
    arr.forEach(num => {
      const p = demo.appendChild(document.createElement('p'));
      p.textContent = num;
      p.addEventListener('click', () => {
        arr.splice(arr.indexOf(num), 1);
        p.remove();
        console.log('now have ' + JSON.stringify(arr));
      });
    });
    <div id="demo">
    
    </div>

    I'd recommend avoiding getElementsByClassName. The getElementsBy* methods return HTMLCollections, which can be difficult to work with. Consider using querySelectorAll instead, which returns a static NodeList - unlike an HTMLCollection, it can be iterated over directly, it won't change while it's being iterated over, and it's much more flexible.

  • answered 2018-04-17 05:49 Sachi Tekina

    Modifying you code, I have came up with this:

    var arr = [10, 20, 30];
    
    var demo = document.getElementById('demo');
    for (var i = 0; i < arr.length; i++) {
      demo.innerHTML += `<p class="tag">${arr[i]} </p>`;
    }
    
    var pTag = document.getElementsByClassName("tag");
    for (var j = 0; j < pTag.length; j++) {
      pTag[j].onclick = function() {
        console.log(this.innerText);
        this.remove();
        var num = parseInt(this.innerText);
        arr.splice(arr.indexOf(num), 1);
        console.log(arr)
      }
    }
    <div id="demo">
    
    </div>

  • answered 2018-04-17 05:50 Sreekanth

    Here is what you could do.

    var arr = [10, 20, 30];
    
    var demo = document.querySelector('#demo');
    for (var i = 0; i < arr.length; i++) {
      demo.innerHTML += `<p class="tag">${arr[i]} </p>`;
    }
    
    demo.addEventListener('click', function(event) {
      event.target.remove();
    });
    <div id='demo'>
    </div>