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

Viewed 49037

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

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
Related