jQuery select ancestor

后端 未结 6 1977
清酒与你
清酒与你 2020-12-24 06:44

Is is possible to use jQuery to select an ancestor of an element?

Markup:


      
      
6条回答
  •  自闭症患者
    2020-12-24 07:00

    You mean something like this?

    $('.click-me').click(function() {
        var $theAncestor = $(this).closest('#ancestor-1');
    }
    

    This will search through all ancestors until a match is found.

    http://api.jquery.com/closest/

    EDIT:

    Jerome, your question can be interpreted several ways. This speaks to the power and flexibility of jQuery.

    Please consider the following.

    First, to answer your question, yes, it is possible to use jQuery to select an ancestor of an element.

    I think we can assume that you are aware of jQuery's ability to select any element, whether ancestor or descendant via:

    $('#myElement')
    

    Given the click-me example, if you would like to have a set of all of an element's ancestors returned, use:

    $(this).parents()
    

    or

    $(this).parents(selector)
    

    But be aware that this will traverse through ALL ancestors returning all, or all that match when a selector is given.

    If you would like to have the immediate parent returned, use:

    $(this).parent()
    

    If you know which ancestor you need, use:

    $(this).closest(selector)
    

    But be aware that it will only return the first match, and if the current element (this) is a match, it will return that.

    I hope this helps.

提交回复
热议问题