JQuery, find parent

后端 未结 7 1611
日久生厌
日久生厌 2021-01-31 02:15
$(\'#thisid\').parent(\'li\');
相关标签:
7条回答
  • 2021-01-31 02:53

    I prefer the 'closest' than 'parents'.

    Parents travel up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied.

    where

    Closest Travel up the DOM tree until it finds a match for the supplied selector.

    Most important what they give in result:

    Praents: Returned jQuery object contains zero or more elements for each element in the original set, in reverse document order.

    Closest: Returned jQuery object contains zero or one element for each element in the original set, in document order

    $('#thisid').closest('li');
    

    Follow this Link

    0 讨论(0)
  • 2021-01-31 03:00
    $('li').has('#thisid')
    

    http://api.jquery.com/has/

    0 讨论(0)
  • 2021-01-31 03:02
    $('#thisid').parents('li')
    

    or if you only want the first one:

    $('#thisid').closest('li')
    
    0 讨论(0)
  • 2021-01-31 03:03
    $('#thisid').parents( 'li:eq(0)' ); 
    

    Should do it. This will give you the first (:eq(0)) parent that matches being the tag you're searching for.

    0 讨论(0)
  • 2021-01-31 03:07
    $('#thisid').parents('li');
    //                 ^ plural!
    

    Note that if you only want the first <li> element in the ancestry, you should use closest():

    $('#thisid').closest('li');
    
    // `closest()` is equivalent to (but performs better than)
    $('#thisid').parents('li').eq(0);
    $('#thisid').parents('li').first();
    
    • http://api.jquery.com/closest/
    • http://api.jquery.com/parents/
    0 讨论(0)
  • 2021-01-31 03:09

    Simple, use parents()

    var parents = $("#thisid").parents('li');
    
    0 讨论(0)
提交回复
热议问题