Déjà Bond Déjà Bond - 29 days ago 10
Javascript Question

Check if <p> is first child

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>

Answer

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:

Comments