How to select first child with jQuery?

前端 未结 5 992
暗喜
暗喜 2020-11-28 08:25

How do I select the first div in these divs (the one with id=div1) using first child selectors?

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 08:30

    Use the :first-child selector.

    In your example...

    $('div.alldivs div:first-child')
    

    This will also match any first child descendents that meet the selection criteria.

    While :first matches only a single element, the :first-child selector can match more than one: one for each parent. This is equivalent to :nth-child(1).

    For the first matched only, use the :first selector.

    Alternatively, Felix Kling suggested using the direct descendent selector to get only direct children...

    $('div.alldivs > div:first-child')
    

提交回复
热议问题