Abhishek Dhanraj Shahdeo Abhishek Dhanraj Shahdeo - 1 month ago 8
HTML Question

click event not firing on anchor tag

My click event is not firing :

html


<tr>
<td>121345</td>
// Other td elements
<td><a href = "#" class = "remove-item">Remove</a></td>
</tr>


javascript


window.document.load = function() {
document.getElementsByClassName('remove-item').onClick(function(element) {
console.log("element");
var productId = element.parentElement.parentElement.childElements[0].value;
console.log(productId);
})
}


I don't want to use jquery here

Answer

You did some errors there:

  • document.getElementsByClassName returns multiple elements
  • .onClick(...) is not the way to add an onclick handler

This snippet will remove the parenting <tr> element on click of an remove button:

var items = document.getElementsByClassName('remove-item');
for(var i = 0; i < items.length; i++)
{
  var item = items[i];
  item.onclick = function(e)
  {
    e.target.parentNode.parentNode.style.display = "none";
  };
}
<table>
  <tr>
    <td>Test 1</td>
    <td><a href="#" class="remove-item">Remove</a></td>
  </tr>
  <tr>
    <td>Test 2</td>
    <td><a href="#" class="remove-item">Remove</a></td>
  </tr>
  <tr>
    <td>Test 3</td>
    <td><a href="#" class="remove-item">Remove</a></td>
  </tr>
</table>