Jasser Amri
Jasser Amri

Reputation: 25

How can I use 'this' to target a specific div in a function?

I making a shopping cart website. I need to set up a delete button per product and I want to call the same delete function with this every time. Can you help me understand what I did wrong? excuse me for not using proper terminology as I am new to coding.

This is my function to delete products:

function myFunction(element){
  var element = document.getElementById("remove");
  element.parentElement.parentElement.remove();
}

/// this is a snippet of my code for a product row.

<div class="row product">
   <div class="buttons">
        <i class="fas fa-heart" onclick="myHeart(this)"></i>
        <i class="fas fa-times"  id="remove"  onclick="myFunction(this.element)"></i>
  </div>
</div>

I need the specific product row to be deleted every time I click on the delete icon.

Upvotes: 1

Views: 212

Answers (2)

Bentaiba Miled Basma
Bentaiba Miled Basma

Reputation: 587

You need to put this as parameter, not this.element:

<div class="row product">
  <div class="buttons">
     <i class="fas fa-heart" onclick="myHeart(this)"></i>
     <i class="fas fa-times"  id="remove"  onclick="myFunction(this)"></i>
  </div>
</div>

and for your function myFunction(). You don't need to search for element using document.geElementById() because you already have it as a parameter. Here is an update of your function:

function myFunction(element){
  element.parentElement.parentElement.remove();
}

Upvotes: 0

adeneo
adeneo

Reputation: 318312

Change the ID to a class, so it can be reused

<div class="row product">
  <div class="buttons">
    <i class="fas fa-heart"></i>
    <i class="fas fa-times remove"></i>
  </div>
</div>

Add event handlers for those elements

var elems = document.querySelectorAll('.remove');

for (i = 0; i < elems.length; ++i) {
  elems[i].addEventListener('click', function() {
    this.closest('.product').remove();
  });
}

Upvotes: 1

Related Questions