Search code examples
javascriptjquerycross-browserselectorparent

jQuery .parents([selector]) doesn't work with IE9 and Firefox


<html>
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="application/javascript">

        $(document).ready(function() {
            $("#evaluation_complete").parents("table")[0].remove(); //doesn't work

            //this works
            //var EvalComplete = document.getElementById("evaluation_complete");
            //EvalComplete.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(
                //EvalComplete.parentNode.parentNode.parentNode.parentNode); 
        });

    </script>
    <p>Testing little code</p>
    <table>
        <tbody>
            <tr>
                <td class="button-left">&nbsp;</td>
                <td class="button-middle" nowrap="true"><div
                        style="margin: 0px 0px 1px;">
                        <a class="button-text" name="evaluation_complete"
                            id="evaluation_complete" href="#">Evaluation Complete</a>
                    </div></td>
                <td class="button-right">&nbsp;</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

I have no control of how the table is set up. However all I know is the id of the link. My goal is to traverse to the <table> element and remove it from DOM. I've also tried it with closest. The error I get in Firefox and IE9 is that remove is not a function. The commented out block works but is not very dynamic. However, in Chrome, it works flawlessly. Thank you for any help.


Solution

  • It does'nt work as you are trying to use .remove() on a native JS element, not a jQuery element:

    It's not :

    $("#evaluation_complete").parents("table")[0].remove();
    

    but

    $("#evaluation_complete").parents("table").eq(0).remove();
    

    or

    $("#evaluation_complete").parents("table").first().remove();
    

    etc.

    using [0] or get(0) gets the native JS element from the array-like jQuery object, which does'nt have a .remove() method.

    As a sidenote, using closest() would be more efficient, and will work with the above examples.