jQuery first of type selector?

后端 未结 6 2030
独厮守ぢ
独厮守ぢ 2021-01-03 18:35

How would I select the first

element in the following

with jQuery?

heading

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 19:16

    Assuming you have a reference to the div already:

    $(yourDiv).find("p").eq(0);
    

    If the first p will always be a direct child of the div, you could use children instead of find.

    Some alternatives include:

    $(yourDiv).find("p:eq(0)"); //Slower than the `.eq` method
    $(yourDiv).find("p:first"); 
    $(yourDiv).find("p").first() //Just an alias for `.eq(0)`
    

    Note that the eq method will always be the fastest way to do this. Here's the results of a quick comparison of the eq method, :eq selector and :first selector (I didn't bother with the first method since it's just an alias of eq(0)):

    enter image description here

提交回复
热议问题