2

I have several clickable HTML elements that all use the same JS function when clicked.

Now when one of "floor" is clicked I want it to remove that "tile" div and "floor" div.

<div class="col">
  <div class="tile">
    <div class="floor" onclick="killTile()"></div>
  </div>
  <div class="tile">
    <div  class="floor" onclick="killTile()"></div>
  </div>
  <div class="tile">
    <div class="floor" onclick="killTile()"></div>
  </div>
</div>
<div class="col">
  <div class="tile">
    <div class="floor" onclick="killTile()"></div>
  </div>
  <div class="tile">
    <div class="floor" onclick="killTile()"></div>
  </div>
  <div class="tile">
    <div class="floor" onclick="killTile()"></div>
  </div>
</div>

killTile function:

function killTile(){
    // Play explosion sound effect
    xpld.pause();
    xpld.currentTime = 0;
    xpld.play();
}

3 Answers 3

2

Give the function a parameter:

function killTile(which) {
    // Play explosion sound effect
    xpld.pause();
    xpld.currentTime = 0;
    xpld.play();
    var tilediv = which.parentNode;
    tilediv.parentNode.removeChild(tilediv);
}

Then call it as:

<div class="floor" onclick="killTile(this)"></div>
Sign up to request clarification or add additional context in comments.

Comments

1

In order to remove a DOM node you can use removeChild method:

function killTile(obj) {
    // Play explosion sound effect
    xpld.pause();
    xpld.currentTime = 0;
    xpld.play();

    // remove parent node
    obj.parentNode.parentNode.removeChild(obj.parentNode);
}

and pass obj as:

<div class="tile">
    <div  class="floor" onclick="killTile(this)"></div>
</div>

Comments

0

You can simply use this..

function killTile(obj){
    // Play explosion sound effect
    xpld.pause();
    xpld.currentTime = 0;
    xpld.play();

    obj.parentElement.remove();
}

Call it like onClick="KillTile(this)"

2 Comments

This just removes the floor, not the tile.
Oops, I thought you were using removeChild, like the other answers. The problem with remove is that it's new, and not as compatible as removeChild. If you edit your answer to include caveats, I'll be able to remove my downvote.

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.