jQuery first of type selector?

2020-03-01 02:43发布

How would I select the first <p> element in the following <div> with jQuery?

<div>
    <h1>heading</h1>
    <p>How do I select this element with jQuery?</p>
    <p>Another paragraph</p>
</div>

6条回答
叛逆
2楼-- · 2020-03-01 03:19

$("div p").first();

or $('div p:first');

Reference: http://api.jquery.com/first/

Keep in mind that first() matches only a single element, the :first-child selector can match more than one: one for each parent.

查看更多
放我归山
3楼-- · 2020-03-01 03:22

This should work

$( "div p:first-of-type" ).css( "font-size: 10px" );

The above code finds the first paragraph in the div as @Denver pointed and changed its fonts-size to 10px

Here is an example that explains even more about jQuery first-of-type selector

查看更多
老娘就宠你
4楼-- · 2020-03-01 03:28
$('div p:first')

answer was too short to post without this useless sentence.

Edit This is definitely a slow option. After looking at Jame's speed test, it looks like jQuery selectors work best when they piggy back off of css selectors.

查看更多
Rolldiameter
5楼-- · 2020-03-01 03:35

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

查看更多
Evening l夕情丶
6楼-- · 2020-03-01 03:41

You almost know the answer (from your post title). There is a selector in jQuery called :first-of-type. Use it to find and add class to the first p tag automatically, like so:

$("div p:first-of-type").addClass('someClass');
查看更多
Root(大扎)
7楼-- · 2020-03-01 03:43
$('div p').first()

Should work. I think.

查看更多
登录 后发表回答