3

I need to delete multiple canvas elements created. With the function below I can delete one every time I click a button but I need to delete all canvas created at once. How can I do this?

function deleteCanvas() {
  var list = document.getElementById("output");
  list.removeChild(list.childNodes[0]);
}
2
  • 2
    can you post your html file? Commented Nov 22, 2019 at 18:42
  • are all of your canvas elements contained inside the "output" element? Commented Nov 22, 2019 at 18:49

3 Answers 3

4

You can use while and as long as there are child elements in the list, keep removing them:

function deleteCanvas() {
  var list = document.getElementById("output");
  while(list.childNodes.length) {
    list.removeChild(list.childNodes[0]);
  }
}
canvas {
 width: 10px;
 height: 10px;
 outline: solid red 1px;
}
<div id="output">
  <canvas></canvas>
  <canvas></canvas>
  <canvas></canvas>
  <canvas></canvas>
</div>

<button onclick="deleteCanvas()">delete all canvas elements</button>

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

1 Comment

Note this will indiscriminately remove all nodes in the parent element and not check if it is removing a canvas element or not. Also childNodes includes text nodes so you might accidentally remove non-empty text nodes. children might be a better option as it only contains elements.
3

querySelectorAll, and the various getElementsBy* methods can select multiple elements. Just loop over the returned list and remove() as nessary

For instance if you have a bunch of <canvas class="game"> elements that you want removed you can use the canvas.game css selector with querySelectorAll, or passing game to getElementsByClassName to target those specific elements (leaving other canvas elements alone):

let list = document.querySelectorAll('canvas.game');
//or
let list = document.getElementsByClassName("game");

for(let i=0; i<list.length; i++){
  list[i].remove();
}

2 Comments

@FZs they do: developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove and there is a polyfill for older browsers (IE)
Oh yes, I see! I didn't know about it! I've always used node.parentNode.removeChild(node) for this... until now. +1
1

Maybe like this ?

let canvasses = document.getElementsByTagName("canvas");
//you can also do this with classes.

while (canvasses.length > 0) {
    for (let i =0; i < canvasses.length; i++) {
        canvasses[i].remove();
    }
}

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.