Why am I getting the wrong parent node in my function?

I want to get the parent node of the button, which should be an element td, but instead I get the element body. What causes this? I want to use only JavaScript, not jQuery.

This is my code:

<html>
<head>
   <meta charset="utf-8">
</head>
    <body>
        <tr>
            <td><input type='text'></td>
            <td><button class='clk' onclick="g(this)">click me!</button></td>
        </tr>
        <script src="jquery/jquery.min.js"></script>
        <script>
            function g(c) {
                alert(c.parentNode.nodeName);
            }
        </script>
    </body>
</html>
+4
source share
1 answer

The problem is that you have invalid html without putting <tr>in <table>. The browser then rejects it and meets <td>that does not have a valid parent, and then meets <button>that does not have a valid parent and ends with <body>.

When you provide the wrong html markup, you get unexpected results.

<tr> <table></table> <tbody>, <thead> <tfoot> <table>

, , .

DEMO

+4

All Articles