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

前端 未结 10 1964
北荒
北荒 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:19

    For people who want a vanilla JS solution:

    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
    

提交回复
热议问题