UltimateSky
UltimateSky

Reputation: 41

How to remove the div that a button is contained in when the button is clicked?

I am trying to remove a div when the button inside of it is clicked.

HTML

<html>
    <head>
        <script src="test.js"></script>
    </head>
    <body>
        <div class="image">
            <img src="http://i.imgur.com/VuKnN5P.jpg" alt="First">
            <button class="remove">X</button>
        </div>
        <div class="image">
            <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
            <button class="remove">X</button>
        </div>
    </body>
</html>

Javascript

function registerClickHandler() {
  // Register click event handler for button of class 'remove'
    "use strict";
    var node = document.getElementsByClassName("image");
    if (node.parentNode) {
        node.parentNode.removeChild(node);
    }
}

var listen = document.getElementbyClassName("remove");
listen.addEventListener("click", registerClickHandler());

So when I click the 'X' button inside of the div, I need it to remove the entire parent div, but it seems like nothing I've tried will work. I'm not sure if maybe I'm not using event handlers the right way or not, or if something I'm doing is just completely wrong. I would like to do this without using jQuery (because I don't really know it) if possible, but a lot of the solutions I've seen for vaguely similar problems have all used jQuery.

Edit: I forgot to specify that I am looking for a way to accomplish this using eventHandlers.

Upvotes: 4

Views: 22533

Answers (10)

Mr. Benedict
Mr. Benedict

Reputation: 827

I prefer this approach:

<button type="button" onclick="return this.parentNode.remove();">Remove</button>

Also works if the parent element and its children were dynamically created.

Upvotes: 1

JVal aka SolidSnake
JVal aka SolidSnake

Reputation: 281

Try Element.closest() you can change element selector by pref

"The Element.closest() method returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter. If there isn't such an ancestor, it returns null."

mind that with a "proper selector" you don't have to worry about the parent or grandparent on elements selection

Here is an example.

function setup() {
    var els = document.getElementsByClassName("remove");
    for (var i = 0; i < els.length; i++) {
        els[i].addEventListener('click', function (e) {
            e.preventDefault();
            e.target.closest('div.image').remove();
        });
    }
}
setup();

img {
  width:100px;  height:100px;
}
<div class="image">
    <img src="http://i.imgur.com/VuKnN5P.jpg" alt="First">
    <button class="remove">X</button>
</div>
<div class="image">
    <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
    <button class="remove">X</button>
</div>

<div class="image">
  <div>
      <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
      <button class="remove">X</button>
  </div>
</div>

<div class="image">
  <div>
      <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
      <button class="remove">X</button>
  </div>
</div>
<script>
    function setup() {
        var els = document.getElementsByClassName("remove");
        for (var i = 0; i < els.length; i++) {
            els[i].addEventListener('click', function (e) {
                e.preventDefault();
                e.target.closest('div.image').remove();
                //e.target.closest('.image').remove();
                
                //this will not work on 2 last images cause parent div will be deleted 
                //leaving an empty <div class="image"></div> for each removed item
                
                //e.target.closest('div').remove();
            });
        }
    }
    setup();
</script>

Upvotes: 5

Brixton Mavu
Brixton Mavu

Reputation: 21

Using Jquery

element = $(".remove");

for (var i in element) {
  element.on('click', function() {
    $(this).parent().remove();
  });
}
<html>

<head>
  <script src="test.js"></script>
</head>

<body>
  <div class="image">
    <img src="http://i.imgur.com/VuKnN5P.jpg" alt="First">
    <button class="remove">X</button>
  </div>
  <div class="image">
    <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
    <button class="remove">X</button>
  </div>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

</body>

</html>

Upvotes: 1

Farid Ansari
Farid Ansari

Reputation: 841

try this...

const registerClickHandler = ()  => {
x = document.getElementsByClassName("remove") 
for(var i = 0; i<x.length; i++){ 
           x[i].addEventListener("click",function(current){
               current.srcElement.parentElement.remove();
           });
          }
        }

Upvotes: 0

Jeffery
Jeffery

Reputation: 134

It looks like the button tag does not have onclick function. For this, you need to self invoke function. Here is my answer.

(function registerClickHandler() {
   var classLength = document.getElementsByClassName("remove").length;
   for(var i = 0; i<classLength; i++){ 
   document.getElementsByClassName("remove")
   [i].addEventListener("click",function(current){
       current.srcElement.parentElement.remove();
   });
  }
 })();

Upvotes: 0

Vinoth kanna
Vinoth kanna

Reputation: 45

Easiest way to remove the parent element

function removeParent(parent) {
	parent.remove();
}
  <html>
    <head>
        <script src="test.js"></script>
    </head>
    <body>
        <div class="image">
            <img src="http://i.imgur.com/VuKnN5P.jpg" alt="First">
            <button class="remove" onclick ="removeParent(this.parentNode)">X</button>
        </div>
        <div class="image">
            <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
            <button class="remove" onclick ="removeParent(this.parentNode)">X</button>
        </div>
    </body>
</html>

Upvotes: 0

arlendp
arlendp

Reputation: 95

You can try this

<html>
    <head>
        <script src="test.js"></script>
    </head>
    <body>
        <div class="image">
            <img src="http://i.imgur.com/VuKnN5P.jpg" alt="First">
            <button class="remove">X</button>
        </div>
        <div class="image">
            <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
            <button class="remove">X</button>
        </div>
        <script type="text/javascript">
            function removeParent() {
                this.parentNode.remove();
            }
            var buttons = document.getElementsByClassName('remove');
            Array.prototype.forEach.call(buttons, function(d, i) {
                d.addEventListener('click', removeParent);
            });
        </script>
    </body>
</html>

Upvotes: 0

Damon
Damon

Reputation: 4346

getElementbyClassName is the wrong syntax. You're looking for getElementsByClassName. This returns an array like object (HTMLCollection), not a node, and you will need to apply the event listener to each element individually. You also don't need to use removeChild. That's a bit redundant.

var els = document.getElementsByClassName('remove');

for (var i = 0; i < els.length; i++) {
  els[i].addEventListener('click', function () {
    this.parentNode.remove();
  });
}
<div class="image">
  <img src="http://i.imgur.com/VuKnN5P.jpg" alt="First">
  <button class="remove">X</button>
</div>
<div class="image">
  <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
  <button class="remove">X</button>
</div>

Upvotes: 3

Your javascript code is having issues. The working code is

function registerClickHandler() {
  // Register click event handler for button of class 'remove'
   "use strict";
   this.parentNode.parentNode.removeChild(this.parentNode);
}
var listen = document.getElementsByClassName("remove");
var i;
for (i = 0; i < listen.length; i++) {
	listen[i].addEventListener("click", registerClickHandler);
}
  <div class="image">
            <img src="http://i.imgur.com/VuKnN5P.jpg" alt="First">
            <button class="remove">X</button>
        </div>
        <div class="image">
            <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
            <button class="remove">X</button>
        </div>

Now, Issues

  1. wrong function call at var listen = document.getElementbyClassName("remove");
  2. Function returns an array. you have to loop over it.
  3. To refer to clicked element in function need to use this
  4. Last to remove parent element you need to refer parent of parent. Then remove this.parent.

.

Upvotes: 0

Lahiru Ashan
Lahiru Ashan

Reputation: 767

This should work,

<html>
<head>
    <script src="test.js"></script>
    <script type="text/javascript">
        function removeDiv(btn){
            ((btn.parentNode).parentNode).removeChild(btn.parentNode);
        }
    </script>
</head>
<body>
    <div class="image">
        <img src="http://i.imgur.com/VuKnN5P.jpg" alt="First">
        <button class="remove" onclick="removeDiv(this);">X</button>
    </div>
    <div class="image">
        <img src="http://i.imgur.com/ee4QOKe.jpg" alt="Second">
        <button class="remove" onclick="removeDiv(this);">X</button>
    </div>
</body>
</html>

Upvotes: 3

Related Questions