jquery parent select - more efficient way

前端 未结 2 526
野趣味
野趣味 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条回答
  • 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

    0 讨论(0)
  • 2021-01-19 15:39

    If you have an id, class or tagname to go by you can do $(draggable).parents(element). But make sure it's unique enough that you'll get only one element, as parents() will retrieve multiple elements if found.

    0 讨论(0)
提交回复
热议问题