jQuery parent of a parent

前端 未结 9 1473
执笔经年
执笔经年 2020-12-02 05:40

I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a , and I\'d like to get the

相关标签:
9条回答
  • 2020-12-02 06:05

    If you have any sort of id/class for the parent, you can use parents() but that will give you all parents up to the < body > unless you filter() or stop it some other way like

    $(this).parents('.myClass');
    

    Hope this helps someone :)

    0 讨论(0)
  • 2020-12-02 06:14

    It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.

    For example:

    $(this).parents("tr:first")
    

    Will find the closest tr "up the chain".

    0 讨论(0)
  • 2020-12-02 06:14

    Try wrapping the $(this).parent() into an jQuery object like $($(this).parent()) I often find the need to do this to make sure I have a valid jquery object. From there you should be able to get a hold of the parents parent, or using the prev() perhaps.

    0 讨论(0)
  • 2020-12-02 06:20
    var getParentNode = function(elem, level) { 
        level = level || 1; 
        for (var i = 0; i < level; i++) {
            if (elem != null) {
                elem = elem.parentNode; 
            }
        }
        return elem; 
    }
    
    0 讨论(0)
  • 2020-12-02 06:22

    .closest() is not always best option specially when you have same element construct.

    <div>
        <div>
            <div>
            </div>
        </div>
    </div>
    

    You can do parent of a parent and it's very easy:

    var parent = $('.myDiv').parent();
    var parentParent = $(parent).parent();
    var parentParentParent = $(parentParent).parent();
    

    etc.

    0 讨论(0)
  • 2020-12-02 06:26

    also try

    $(this).closest('div.classname').hide();
    
    0 讨论(0)
提交回复
热议问题