Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.parent() doesn't appear to be working

Tags:

jquery

parent

.parent() is not returning the parent element that I'm specifying. I don't see any problems with my code or html.

Javascript:

var vehicle = function () {
    return {
        init: function () {
            var that = this;

            jQuery('.vehicle-year-profile .options .delete').bind('click', function (e) {
                e.preventDefault();
                console.log(e.currentTarget); //  [a.close #]
                that.remove(jQuery(e.currentTarget).parent('.vehicle-year-profile'));
            });
        },
        remove: function (el) {
            console.log(el); // []
            jQuery(el).remove();
        }
    }
}();
jQuery(function() {
    vehicle.init();
});

HTML:

    <div id="vehicle-101031994" class="vehicle-year-profile">
                                        <div class="left">
                                            <h4>1994</h4>
                                        </div>
                                        <div class="right options">
                                            <a class="edit" href="#"><img class="icon-small" src="/image/icons/pencil.png"></a>
                                            <a class="delete" href="#"><img class="icon-small" src="/image/icons/delete.png"></a>
                                        </div>
                                        <div class="clear"></div>
</div>
like image 479
Webnet Avatar asked Dec 22 '22 23:12

Webnet


2 Answers

This is because

The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.

the parent you are looking for is two levels up, so you'll have to use .parents() (or even better .closest()).

like image 71
Pekka Avatar answered Jan 04 '23 23:01

Pekka


The element you're referencing is not a direct parent.

Try this instead:

that.remove(jQuery(this).closest('.vehicle-year-profile'));
like image 24
user113716 Avatar answered Jan 04 '23 22:01

user113716