1

Right now I have this code:

<script type="text/javascript">
   function delete_box(n) {
     document.getElementById("box"+n).style.display = "none";
   }
<script>

<div id="box1">
 <table>
  <td>some code</td><td><input type="button" value="Delete this box" onclick="delete_box(1)"></td>
 </table>
</div>

It works fine. When I press the button the box disappears. However I want to simplify and have it like this:

<script type="text/javascript">
   function delete_box(n) {
     document.getElementById(n).style.display = "none";
   }
<script>

<div id="box1">
 <table>
  <td>some code</td><td><input type="button" value="Delete this box" onclick="delete_box(this.parentnode.id)"></td>
 </table>
</div>

However it wont work as intended. The console says that the id is null and I'm not sure why. What have I done wrong?

Thank you.

JSON C11
  • 11,272
  • 7
  • 78
  • 65
Cain Nuke
  • 2,843
  • 5
  • 42
  • 65

2 Answers2

5

At first, the property name is .parentNode. Also, you are referring to the wrong ancestor as you have an invalid html structure (browser has corrected it as you can see in the html inspector), so using you approach you should have written something like this :

delete_box(this.parentNode.parentNode.parentNode.parentNode.parentNode.id)

An explanation is as follows: this is linking to the input element, as you go further up with the .parentNode you get td -> tr -> tbody -> table -> div#box1.

JSFiddle

Community
  • 1
  • 1
potashin
  • 44,205
  • 11
  • 83
  • 107
  • Thanks, i didnt know you had to take into account the tbody even if it was not present in the code. – Cain Nuke Dec 04 '14 at 04:41
  • this way of traversing the DOM is brittle. How do I keep traversing until parentNode matches the following conditions - class contains 'cool' AND id is like 'item-' ? – MasterJoe May 17 '20 at 20:44
0

First your HTML is invalid. A td lives inside of a tr, a tr lives inside a thead, tbody, or tfoot element. That element lives inside of a table.

The parent of the button would be a td not the table. You would have to look at multiple parents to get the id.

epascarello
  • 204,599
  • 20
  • 195
  • 236