jquery在标题之后选择任何第一个p元素是否还存在另一个元素

Pae*_*eon 1 html jquery jquery-selectors

我试图改变h2或h3元素之后的第一个p元素,无论是否存在其他元素.

所以html就是这样

<h3>This is the subhead in use</h3>
<img src="http://placehold.it/350x150"/>
<p>Here is some lipsum orum kind of textHere is some lipsum orum kind of textHere is some lipsum orum kind of textHere is some lipsum orum kind of textHere is some lipsum orum kind of text</p>
<p>Here is some lipsum orum kind of textHere is some lipsum orum kind of textHere is some lipsum orum kind of textHere is some lipsum orum kind of textHere is some lipsum orum kind of text</p>
<h3>This is the subhead in use</h3>
<p>Here is some lipsum orum kind of text</p>

<aside>
  <h2>This is the aside title</h2>
  <p>Here is some more lipsum orem. Here is some more lipsum orem. Here is some more lipsum orem. Here is some more lipsum orem.</p>
</aside>
Run Code Online (Sandbox Code Playgroud)

和一些jquery(2.13)

$(function(){
  $('h3, h2').next('p').css({ "color":"green"});    
});
Run Code Online (Sandbox Code Playgroud)

因此,这会在h3或h3标记之后找到第一个p,但如果中间还有另一个元素则找不到它.并不总是,但有时我会想要一个img,div或figure元素和h2或h3,但仍然希望jquery找到第一个p(在上面的代码中,它失败了)

我已经尝试了许多选择器和方法的组合,包括p:first-of-type,siblings,nextAll等.我想这样做而不需要在html部分的第一个p元素中添加一个类.

请帮忙.

Jos*_*ier 5

它没有按预期工作,因为.next('p')只会选择紧接着的p元素.您可以使用该.nextAll()方法选择以下所有p元素(不仅仅是紧随其后的元素),然后链接.first()方法以获取集合中的第一个匹配项:

这里的例子

$('h3, h2').each(function () {
  $(this).nextAll('p').first().css({ "color":"green"});
});
Run Code Online (Sandbox Code Playgroud)