jQuery第一个类型选择器?

如何使用jQuery选择以下

的第一个

元素?

 

heading

How do I select this element with jQuery?

Another paragraph

假设你已经引用了div

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

如果第一个p将永远是div的直接子div ,则可以使用children节点而不是find

一些替代品包括:

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

请注意, eq方法始终是执行此操作的最快方法。 以下是eq方法的快速比较结果:eq选择器和:first选择器(我没有打扰第first方法,因为它只是eq(0)的别名):

在此处输入图像描述

 $('div p:first') 

如果没有这个无用的句子,答案太短了。

编辑这绝对是一个缓慢的选择。 在查看了Jame的速度测试之后,看起来jQuery选择器在从css选择器中退回时效果最好。

$(“div p”)。first();

或$(’div p:first’);

参考: http : //api.jquery.com/first/

请记住,first()只匹配一个元素,:first-child选择器可以匹配多个:每个父元素一个。

你几乎知道答案(来自你的post标题)。 jQuery中有一个名为:first-of-type的选择器。 用它来自动查找并添加类到第一个p标签,如下所示:

 $("div p:first-of-type").addClass('someClass'); 
 $('div p').first() 

应该管用。 我认为。

这应该工作

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

上面的代码在@Denver指向的div中找到div中的第一段,并将其fonts-size更改为10px

这是一个例子,它解释了更多关于jQuery first-of-type选择器的内容