Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 460
Déjà Bond Avatar asked Dec 27 '22 01:12

Déjà Bond


1 Answers

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().
like image 109
David Thomas Avatar answered Jan 08 '23 02:01

David Thomas