jquery 选择标题后的任何第一个 p 元素是否还有另一个元素
jquery selecting any first p element after an heading whether another element is also there
我正在尝试更改 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>
还有一些 jquery (2.13)
$(function(){
$('h3, h2').next('p').css({ "color":"green"});
});
所以这会找到 h3 或 h3 标签后的第一个 p,但如果中间有另一个元素,则找不到它。并非总是如此,但有时我想要 img、div 或图形元素以及 h2 或 h3,但仍然希望 jquery 找到第一个 p(在上面的代码中, 它失败了)
我尝试了多种选择器和方法的组合,包括 p:first-of-type、siblings、nextAll 等。我想在不添加 class 的情况下执行此操作html 部分中的第一个 p 元素。
请帮忙。
它没有按预期工作,因为 .next('p')
will only select the immediately following p
element. You could use the .nextAll()
method 到 select 所有以下 p
元素(不仅仅是紧随其后的元素),然后将 .first()
方法链接到获取集合中的第一个匹配项:
$('h3, h2').each(function () {
$(this).nextAll('p').first().css({ "color":"green"});
});
我正在尝试更改 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>
还有一些 jquery (2.13)
$(function(){
$('h3, h2').next('p').css({ "color":"green"});
});
所以这会找到 h3 或 h3 标签后的第一个 p,但如果中间有另一个元素,则找不到它。并非总是如此,但有时我想要 img、div 或图形元素以及 h2 或 h3,但仍然希望 jquery 找到第一个 p(在上面的代码中, 它失败了)
我尝试了多种选择器和方法的组合,包括 p:first-of-type、siblings、nextAll 等。我想在不添加 class 的情况下执行此操作html 部分中的第一个 p 元素。
请帮忙。
它没有按预期工作,因为 .next('p')
will only select the immediately following p
element. You could use the .nextAll()
method 到 select 所有以下 p
元素(不仅仅是紧随其后的元素),然后将 .first()
方法链接到获取集合中的第一个匹配项:
$('h3, h2').each(function () {
$(this).nextAll('p').first().css({ "color":"green"});
});