0

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 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.