This the code on jsfiddle http://jsfiddle.net/KGDyR/
I need to add class on (each) p inside (each) div
If the p is the first child of div tag, add class .first
If not add .notfirst
So the output will be like this
<div>
<p class="first">p is first</p>
<img src="http://projectfoo.com/images/foo_logo.gif" />
</div>
<div>
<img src="http://projectfoo.com/images/foo_logo.gif" />
<p class="notfirst">p is not first</p>
</div>
I'd suggest, for simplicity:
$('p').addClass(function(){
return this.previousElementSibling === null ? 'first' : 'notfirst';
});
JS Fiddle demo.
Or, to work in those browsers that don't support previousElementSibling
:
$('p').addClass(function(){
return !$(this).prev().length ? 'first' : 'notfirst';
});
JS Fiddle demo.
References:
addClass()
.Element.previousElementSibling
.prev()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With