Reputation: 69
I am attempting to change the first p element that comes after an h2 or h3 element, whether or not there is another element in between.
So the html for this is
<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>
and some jquery (2.13)
$(function(){
$('h3, h2').next('p').css({ "color":"green"});
});
So this finds the first p after an h3 or h3 tag, but it doesn't find it if there is another element in between. Not always but there will be times when I'd want an img, div, or figure element to come after and h2 or h3, but still want jquery to find that first p (in the above code, it fails)
I have tried a number of combinations of selectors and methods including p:first-of-type, siblings, nextAll, etc. I would like to do this without adding a class to the first p element in the html portion.
Please help.
Upvotes: 1
Views: 1778
Reputation: 240968
It's not working as expected because .next('p')
will only select the immediately following p
element. You could use the .nextAll()
method to select all the following p
elements (not just the immediately following one), then chain the .first()
method to get the first match in the collection:
$('h3, h2').each(function () {
$(this).nextAll('p').first().css({ "color":"green"});
});
Upvotes: 6