user2259263
user2259263

Reputation: 29

this.parentNode returns undefined when run using Firefox

When the following code is run via Firefox and you click the X button, javascript returns tmpField as undefined. I need to get the parentNode of the button which is the div.

<head>
    <title></title>
    <script type ="text/javascript">
        function RemoveItem() {
                if (document.addEventListener) {
                    var container = document.getElementById("InputContainer");
                    var tmpField = this.parentNode;
                    alert("Field: " + tmpField);                 
                }
        }
    </script>
</head>
<body>
<table width="100%">
<tr>
    <td style="width: 10%; vertical-align:top;">Field:</td>
    <td id="InputContainer">
        <div id="divInput1" style="display: inline;">
            <input id="txtComment1" name="txtComment" type="text" maxlength="35" />
            <input id="btnDelete1" value="X" type="button" name="btnDelete" onclick="RemoveItem()" />
        </div>
    </td>
</tr>
</table>
</body>
</html>

In my scenario, I dynamically create multiple divs within "InputContainer". Each of those divs has the same structure containing a text box and the delete button (with IDs containing the next increment). It is important for me to be able to return the parentNode of the button which will always be the div. I have the code for it to work in IE but not Firefox. Any ideas how to resolve?

Thanks...

Upvotes: 1

Views: 4007

Answers (1)

Ian
Ian

Reputation: 50933

Use this HTML:

<input id="btnDelete1" value="X" type="button" name="btnDelete" onclick="RemoveItem(this)" />

And this JS:

function RemoveItem(button) {
    var container = document.getElementById("InputContainer");
    var tmpField = button.parentNode;
    alert("Field: " + tmpField);
}

DEMO: http://jsfiddle.net/jwpds/1/

The context of the RemoveItem function call is global, so this refers to window. To get the specific element clicked, you need to pass this in the function call, and then access it as an parameter in the function.

And I have no idea why you were checking for document.addEventListener, but I can assure you, you don't need it with what you are doing.

Upvotes: 1

Related Questions