nearest ancestor node in jQuery

后端 未结 4 1744
情歌与酒
情歌与酒 2021-01-07 23:53

In my javascript experience, I found that is a very common task \"searching the nearest ancestor of an element with some condition (tag name, class,...)\". Can the parents(

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-08 00:47

    You should use closest, because parents won't give you the result you expect if you're working with multiple elements. For instance, let's say you have this:

        
    test with nested divs.
    another div.
    yet another div.

    and you want to add a class to the divs that have a element as their immediate child (ie, 1 and 3). If you use $('b').parents('div'), you get divs 0, 1 and 3. If you use $('b').parents('div:first'), you only get div 1. To get 1 and 3, but not 0, you have to use $('b').closest(elem).

提交回复
热议问题