0

I am programming a blackjack game and for each drawn card i create a tag <img> to display the card. Naturally i have to delete this tag <img> after every game, but how can i do this?

Is there a way that I can remove all <img> tags within a parent?

Is there something like this: (Pseudecode)

div.removeAllChildElemtens()

or

div.removeChildElements("img");

Thanks.

3
  • you can set innerHTML="" Commented May 28, 2014 at 11:25
  • i dont know how many IMG tags exactly be generated, because the cards differ in every game.. so i need a way to just delete this IMG tags at every new game started... Commented May 28, 2014 at 11:26
  • append a classname to the images you want to delete later on. so you can use getElementsByClassName("to-delete") or something like that Commented May 28, 2014 at 11:29

2 Answers 2

1

If you create the elements using document.createElement('img') then you can keep a reference to them in order to delete them later.

var cards = [];
for (var i = 0; i < 52; i++)
{
    var card = document.createElement('img');
    // ... more initialisation of card
    cards.push(card);
}

// later, to remove all

for (var i = 0; i < cards.length; i++)
{
    var card = cards[i];
    card.parentElement.removeChild(card);
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very much. With this, it is working fine now. Thanks.
0

Please, see the removeChild usage trick or use the new remove() function:

var div = document.getElementById("parentDivId");
var images = div.getElementsByTagName('img');

for(var i = 0; i < images.length; i++){
    var img = images[i];
    img.parentNode.removeChild(img);
   //OR img.remove() as @Pete TNT pointed-out for modern web-browsers (FF/CH < 23)
}

2 Comments

Isn't remove() jQuery?
ChildNode.remove() is also supported by few modern browsers (FF/CH < 23) developer.mozilla.org/en-US/docs/Web/API/ChildNode.remove

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.