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

前端 未结 10 1938
北荒
北荒 2021-01-01 10:26

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

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

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


        
相关标签:
10条回答
  • 2021-01-01 11:12

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

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

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

    0 讨论(0)
  • 2021-01-01 11:13

    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
    }
    
    0 讨论(0)
  • 2021-01-01 11:19

    For people who want a vanilla JS solution:

    <div id="parent">
      <div id="child-1"></div>
      <div id="child-2"></div>
      <div id="child-3"></div>
    </div>
    
    let element = document.getElementById('child-1');
    console.log(element.parentElement.firstElementChild === element); // true
    console.log(element.parentElement.lastElementChild === element);  // false
    
    element = document.getElementById('child-2');
    console.log(element.parentElement.firstElementChild === element); // false
    console.log(element.parentElement.lastElementChild === element);  // false
    
    element = document.getElementById('child-3');
    console.log(element.parentElement.firstElementChild === element); // false
    console.log(element.parentElement.lastElementChild === element);  // true
    

    It's not the most elegant thing but it gets the job done.

    You can even check if it's the nth element in the same fashion.

    let n = 2; // check if it's the 2nd child
    
    let element = document.getElementById('child-2');
    // index starts at 0
    console.log(element.parentElement.children[-1 + n] === element); // true
    
    0 讨论(0)
  • 2021-01-01 11:19

    jQuery .not()

    $(this).not(':first');
    
    0 讨论(0)
  • 2021-01-01 11:21

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

    $('#some-parent').children().not(':first')
    
    0 讨论(0)
  • 2021-01-01 11:21
    $("li").click(function(e) {
       if ($(this).index != 0 )
      {
          /* do something */
       }
    });
    
    0 讨论(0)
提交回复
热议问题