jquery parent select - more efficient way

前端 未结 2 549
野趣味
野趣味 2021-01-19 14:58

Is there are more efficient way than the following for selecting the third parent?

$(draggable).parent().parent().parent().attr(\'entityid\')
2条回答
  •  猫巷女王i
    2021-01-19 15:37

    This should be faster, since we're using pure DOM instead of repeatedly attaching the parent to the jQuery object.

    jQuery.fn.getParent = function(num) {
        var last = this[0];
        for (var i = 0; i < num; i++) {
            last = last.parentNode;
        }
        return jQuery(last);
    };
    // usage:
    $('#myElement').getParent(3);
    

    Working demo: http://jsbin.com/ecoze

提交回复
热议问题