How to check if the element is not the first-child

2019-02-11 16:16发布

问题:

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 */
    }
});

回答1:

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.



回答2:

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

$(this).index();   // returns a zero based index position


回答3:

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

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

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



回答4:

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

$('#some-parent').children().not(':first')


回答5:

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
}


回答6:

Check the index

$(this).index() == 0 // is first


回答7:

Keep it simple, use the DOM


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

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

});


回答8:

jQuery .not()

$(this).not(':first');


回答9:

$("li").click(function(e) {
   if ($(this).index != 0 )
  {
      /* do something */
   }
});