views:

106

answers:

8

How do you know if the current element is not the first-child?

It should work with $(this), for example:

$("li").click(function(e) {
    if (/* $(this) is not the first-child */)
    {
        /* do something */
    }
});
+3  A: 

For all li's in #thing that aren't first child:

$('#thing li:not(:first-child)')

see http://api.jquery.com/not-selector/

Litso
+3  A: 

If you would like to select everything except the first child, this is how to do it:

$('#some-parent').children().not(':first')
elusive
+7  A: 

You can do this just to test an element if it's the first child: $(this).is(':first-child'). Other selectors like :last-child would work too.

Reinis I.
That will return `true` for everything... `:first` would check that it is the first item in the jQuery set, I believe you might want `:first-child`
gnarf
Sorry, you're right, I fixed it.
Reinis I.
Also, `.not(':first-child')` will still return a jQuery set, not a boolean... `.is(':not(:first-child)')`....
gnarf
Sorry again then, I removed that part.
Reinis I.
This solution is returning if the element "is" the first-child when @WorkingHard asked for knowing when "is not" the first-child. Not mentioning that basically all the answer was giving away by @gnarf. I would have liked that @gnarf answered this, and that SO users didn't have voted for a wrong answer (It had at least 3 points when it was all wrong).
Protron
Turning it into "is not" is a matter of adding the `!` operator.
Reinis I.
*shrug* I commented so that he could make his answer better (or at least correct ;) )
gnarf
A: 

jQuery .not()

$(this).not(':first');
Ryan Kinal
`:first` is not the same as `:first-child`, and using `.not(':first')` will *remove* the `:first` item from the set.
patrick dw
+8  A: 

You could simply ask for its .index() position (relative to its siblings).

$(this).index();   // returns a zero based index position
patrick dw
Interestingly enough, `.index()` will return `0` for the first child, which is false, and anything else is true, so therefore, `.index()` actually will return true for anything but the first child... Perfect answer
gnarf
I think it's more of a side-effect of .index(), but nice observation indeed.
Litso
+1  A: 

Check the index

$(this).index() == 0 // is first
BrunoLM
+1  A: 

Also, you can check if $(this).prev().length is defined, like in:

if (!$(this).prev().length){ //This means $(this is the first child
    //do stuff
}
Pjotrovitz
+1  A: 

Keep it simple, use the DOM


$("li").click(function(e) {

    if ($(this).previousSibling != null)
    {
        /* do something */
    }

});
John Doherty
Surely you mean `this.previousSibling` not `$(this).previousSibling` ...
gnarf