Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
113
rated 0 times [  115] [ 2]  / answers: 1 / hits: 15727  / 10 Years ago, thu, december 4, 2014, 12:00:00

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.


More From » html

 Answers
7

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


[#68591] Tuesday, December 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
parker

Total Points: 259
Total Questions: 109
Total Answers: 97

Location: Zambia
Member since Thu, Jun 25, 2020
4 Years ago
;